How do I read data from text file to ArrayList - java

Assume that entered file have the following data:
101
alice
102
bob
103
smith
All this data into textfile, as it's shown in program, just enter text file name and read all data and display.
I wanna read those two data (number and name ) into ArrayList and display all the data as what I've shown in the program:
class Student {
private int num;
private String name;
public Student(int num, String name) {
this.num = num;
this.name= name;
}
public String toString() {
return "[ student number :: "+num+" ] \t [ student name ::
"+name+ "]";
}
}
import java.io.*;
import java.util.*;
class Tester {
public static void main(String [] aa)throws IOException {
Scanner kb=new Scanner(System.in);
System.out.print(" enter file name >> ");
String filename=kb.nextLine();
File f = new File(filename);
kb=new Scanner(f);
ArrayList<Student> stu =new ArrayList<Student>();
while(kb.hasNextLine()) {
int num=kb.nextInt();kb.nextLine();
String name =kb.nextLine();
stu.add(num);
stu.add(name);
}
for(int i=0;i<stu.size(); i++) {
System.out.println(stu.get(i));
}
}
}

Since you already made an arraylist of student you can do this inside your text reader(while loop): stu.add(new Student(num, name)); what it does is you are creating an object of student and placing it inside the arraylist for every record in your text file.

Your program should return an error because are attempting to put a String and int into an ArrayList of Students. Also, you only iterates through your ArrayList of students and do not print them out. Your code should look like this.
class Tester {
public static void main(String[] aa) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.print(" enter file name >> ");
String filename = kb.nextLine();
File f = new File(filename);
kb = new Scanner(f);
ArrayList<Student> stu = new ArrayList<Student>();
while (kb.hasNextLine()) {
int num = kb.nextInt();
kb.nextLine();
String name = kb.nextLine();
stu.add(new Student(num, name));
}
for (Student s : stu) {
System.out.println(s.toString());
}
}
}

public class Tester {
public static void main(String[] args) {
String path = "E:\\b.txt";
Tester tester = new Tester();
String[] str = tester.sortData(tester.readFile(path));
List<Student> list = new ArrayList<Student>();
for(int i = 0;i < str.length;i = i + 2){
Student student = new Student();
student.setNum(Integer.parseInt(str[i]));
student.setName(str[i + 1]);
list.add(student);
}
for(int i = 0;i < list.size();i++){
System.out.println(list.get(i).getNum() + " " + list.get(i).getName());
}
}
public StringBuilder readFile(String path){
File file = new File(path);
StringBuilder stringBuilder = new StringBuilder();
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
stringBuilder.append(lineTxt);
}
}catch(Exception e){
System.out.println("erro");
}
return stringBuilder;
}
public String[] sortData(StringBuilder words){
int i = 0;
int count = 0;
String str = "\\d+.\\d+|\\w+";
Pattern pattern = Pattern.compile(str);
Matcher ma = pattern.matcher(words);
String[] data = new String[6];
while(ma.find()){
data[i] = ma.group();
i++;
}
return data;
}
}
class Student{
private int num;
private String name;
public Student(){
}
public Student(int num, String name) {
super();
this.num = num;
this.name = name;
}
public String toString() {
return "Student [num=" + num + ", name=" + name + "]";
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Suppose your file looks like this
101 alice
102 bob
103 smith
String fileName = //get by scanner;
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
List<Student> users = new ArrayList<>();
stream.stream().forEach(user -> {
List<String> userAttrs = Arrays.asList(user.split("\\s* \\s*"));
Student userObj = new Student(Integer.parseInt(userAttrs.get(0)), userAttrs.get(1));
users.add(userObj);
});
users.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
After I enter first answer problem was edited and now your file looks like
101
alice
102 bob
103 smith
String fileName = //get by scanner;
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
List<String> detailList = stream.collect(Collectors.toList());
List<Student> students = new ArrayList<>();
BiFunction<String, String, Student> userFunction = (id, name) ->
new Student(Integer.parseInt(id), name);
for (int i = 0; i < detailList.size(); i += 2) {
students.add(userFunction.apply(
detailList.get(i), detailList.get(i+1)));
}
students.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}

Related

Reading from a file into an array of objects

I am trying to read data from a file that I need to be put into my array of objects. When I am trying to read 6 tests from a single student I am getting an error.
I get this error,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
at example.example.readStudentList(example.java:40)
at example.example.main(example.java:57)
how can I make it so I could read the 6 tests pers student and not get out of bounds?
public static Scanner openFile()throws IOException{
File input;
Scanner inFile ;
String fileName;
System.out.print("Enter input file name and path if necessary: ");//e://csc121//data.txt
fileName = KB.nextLine();
input = new File(fileName);
if( ! input.exists()){
System.out.println("File does not exists. Check the file and try again");
System.exit(0);
}
inFile = new Scanner(input); // Step 1 Initialize loop condition
if (! inFile.hasNext()){
System.out.println("Error. Data file has no data.\n");
System.exit(0);
}
return inFile;
}
public static int readStudentList(Student[] stu)throws IOException{
int i = 0;
Scanner inFile;
String name;
String id;
float quiz;
float[] tests = new float[6];
inFile = openFile();
while(inFile.hasNext()){
name = inFile.nextLine();
id = inFile.next();
for(int j = 0; i < 6; j++){
tests[j] = inFile.nextFloat();
}
quiz = inFile.nextFloat();
inFile.nextLine();
stu[i] = new Student(name, id,tests,quiz);
i++;
}
return i;
}
public static void main(String[] args)throws IOException {
Student[] arr = new Student[50];
int size;
size = readStudentList(arr);
System.out.println(size);
System.out.println(arr[0].name);
System.out.println(arr[0].id);
}
}
class Student {
public String id;
public String name;
public float[] tests = new float[6];
public float quiz;
Student(String name, String id, float[] tests, float quiz)
{
this.id = id;
this.name = name;
this.tests = tests;
this.quiz = quiz;
}
}
Take a close look at your for loop:
for(int j = 0; i < 6; j++){
Notice you are incrementing j, but checking the value of i
You have used i in your if statement instead of j. Try the following:
public static int readStudentList(Student[] stu)throws IOException {
int i = 0;
Scanner inFile;
String name;
String id;
float quiz;
float[] tests = new float[6];
inFile = openFile();
while(inFile.hasNext()){
name = inFile.nextLine();
id = inFile.next();
for(int j = 0; j < 6; j++){
tests[j] = inFile.nextFloat();
}
quiz = inFile.nextFloat();
inFile.nextLine();
stu[i] = new Student(name, id,tests,quiz);
i++;
}
return i;
}

Reading a text file from implementation

I am trying to create an implementation that reads a file that the user has typed and submitted. The code for that is located in the SetTester class (shown below). In my implementation I already have an array declared called String[] myArray = new String [] {}; to hold the data from the file. How would I be able to take the file that is being called in the tester class and put it into that array?
public class SetTester
{
public static void main(String [] args) {
StringSet words = new MyStringSet();
Scanner file = null;
FileInputStream fs = null;
String input;
Scanner kb = new Scanner(System.in);
int wordCt = 0;
boolean ok = false;
while (!ok)
{
System.out.print("Enter name of input file: ");
input = kb.nextLine();
try
{
fs = new FileInputStream(input);
ok = true;
}
catch (FileNotFoundException e)
{
System.out.println(input + " is not a valid file. Try again.");
}
}
file = new Scanner(fs);
while (file.hasNext())
{
input = file.next();
words.insert(input);
System.out.println("Current capacity: " + words.getCapacity());
wordCt++;
}
System.out.println("There were " + wordCt + " words in the file");
System.out.println("There are " + words.inventory() + " elements in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
while (!words.contains(input))
{
System.out.println(input + " is not in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
}
words.remove(input);
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("The first 10 words in the set are: ");
for (int x=0; x<10; x++)
System.out.println(words.getFirstItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("5 random words from the set are: ");
for (int x=0; x<5; x++)
System.out.println(words.getRandomItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
}
}
For reading from a file I use this class:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private static String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int j = 0; j < numberOfLines; j++) {
textData[j] = textReader.readLine();
}
textReader.close();
return textData;
}
static int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
then in the class main you can add this code and you edit the path so you can read a file an get an array out of it
public static void main(String args[]) throws IOException {
ReadFile r = new ReadFile("here you put the path that the user provide");
String[] text = r.OpenFile();
ArrayList<String> array = new ArrayList<>();
array.addAll(Arrays.asList(text));
}
If you have any questions let me know!

How to keep ID and Name paired by sorting ID alone?

Currently I am facing a problem during sorting. I can sort my data (in a csv file) using insertion sort by the ID, but i get results like this:
14000027,Sofia Bonfiglio
14000053,Ashlee Capellan
14000310,Dona Mcinnes
14000436,Maricela Landreneau
14000688,Elinor Raco
but the original ID for those names are:
14495655 Sofia Bonfiglio
14224671 Ashlee Capellan
14707100 Dona Mcinnes
14644633 Maricela Landreneau
14147356 Elinor Raco
I am currently stuck. Any tips will help me by a lot, thank you!
Heres my code:
public class NameSorting{
private static void readFiles(String inFileName) throws IOException{
FileInputStream fileStream = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int lineNum;
String line;
try{
fileStream = new FileInputStream(inFileName);
rdr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(rdr);
String[] nameArray = new String[7000];
Long[] idArray = new Long[7000];
String[] rowArray = new String[2];
int i = 0;
lineNum = 0;
line = bufRdr.readLine();
while (line != null){
lineNum++;
rowArray = processLine(line);
//stores the returned split value into two arrays, idArray and nameArray
idArray [i] = Long.parseLong(rowArray[0]);
nameArray [i] = rowArray[1];
i++;
line = bufRdr.readLine();
}
sorts(idArray, nameArray); //sorts the file by id
fileStream.close();
}
catch(IOException e){
if (fileStream != null){
try {
fileStream.close();
}
catch (IIOException ex2){
}
}
System.out.println("Error in file processing" + e.getMessage());
}
}
private static String[] processLine(String csvRow){ //takes in a row from the CSV file and splits it with comma, returns rowArray.
String[] rowArray = new String[2];
rowArray = csvRow.split(",");
return rowArray;
}
private static void write(Long[] idArray, String[] nameArray) {
FileOutputStream fileStrm = null;
PrintWriter pw;
String inFileName = "Sorted.txt";
try {
fileStrm = new FileOutputStream(inFileName);
pw = new PrintWriter(fileStrm);
for (int k = 0; k < idArray.length; k++){
pw.println(idArray[k] + "," + nameArray[k]);
}
pw.close();
} catch (IOException e) {
System.out.println("Error in writing to file: " + e.getMessage());
}
}
private static void sorts(Long[] idArray, String[] nameArray){
for (int pass = 1; pass < idArray.length ; pass++){
int hold = pass;
Long temp = idArray[hold];
while (hold > 0 && (idArray[hold - 1] > temp)){
idArray[hold] = idArray[hold - 1];
hold = hold - 1;
}
idArray[hold] = temp;
}
write(idArray, nameArray);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter file name");
String inp = sc.next();
readFiles(inp);
System.out.println("Done");
}
}
It is possible to solve the problem using a Treemap<Integer, String> using the id as key and after with streams convert the map to an array like below:
public class NameSorting {
public static void main(String[] args) {
String[] lines = {"14495655 Sofia Bonfiglio",
"14224671 Ashlee Capellan",
"14707100 Dona Mcinnes",
"14644633 Maricela Landreneau",
"14147356 Elinor Raco" };
Map<Long, String> map = new TreeMap<>();
for (String line : lines) {
String[] arr = line.split(" ", 2);
map.put(Long.parseLong(arr[0]), arr[1]);
}
String[] mapAsStringArray = map.keySet().stream()
.map(key -> key + "," + map.get(key))
.toArray(String[]::new);
for (String line : mapAsStringArray) {
System.out.println(line);
}
}
}
The output will be ordered:
14147356,Elinor Raco
14224671,Ashlee Capellan
14495655,Sofia Bonfiglio
14644633,Maricela Landreneau
14707100,Dona Mcinnes

How to create a numbered list

I want to create a numbered list, where it shows the index number beside each line. I'm not too sure how to achieve this.
This is the code where i create my list:
public void readFile(Scanner in)
{
inputStudentID = null;
inputMark = 0;
try
{
File file = new File("Marks.txt");
in = new Scanner(file);
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
System.out.println("in " + System.getProperty("user.dir"));
System.exit(1);
}
while (in.hasNextLine())
{
String studentRecord = in.nextLine();
List<String> values = Arrays.asList(studentRecord.split(","));
String inputStudentID = values.get(0);
String sInputMark;
sInputMark = values.get(1);
int inputMark = Integer.parseInt(sInputMark);
addStudent(inputStudentID, inputMark);
}
in.close();
}

Java reading txt file from user input and outputting data according to user input

I have a text file that looks like this
BEG#Belgrave#19 February 1962
FSS#Flinders Street#12 September 1854
TSN#Tecoma#1 February 1924
im trying to write a program, asking the user to input the filename (i can do this part), then the user is prompted to enter in a "Code". The program is then to read the txt file, and output information according the the unique code.
for example:
java Codes
Enter file name >> stationsMaster.txt
Enter station code >> FSS
Station name: "Flinders" has code "FSS" date built: 12 September 1854
here is the code of what i have done so far, im just really stuck on how to write the code so that the program reads through the text file and outputs the according information from the user input.
import java.util.*;
import java.io.*;
public class Codes
{
public static void main (String [] args) throws IOException
{
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter File Name");
String filename = keyboard.nextLine();
File f = new File (filename);
Scanner fin = new Scanner (f);
String stationcode = fin.nextLine();
String stationname = fin.nextLine();
String date = fin.nextLine ();
while (fin.hasNextLine ( ) )
{
System.out.print (date);
System.out.print(stationname);
}
fin.close ();
}
You can try something like this: hope this can solve your problem
public class Test {
private Map<String, Station> stationMap = new HashMap<>();
public static void main(String[] args) throws Exception {
// first read the file and store the data to the map
Test test = new Test();
test.readFile();
// now ask the user for the station code
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Please enter the code: ");
String code = scanner.nextLine();
Station station = test.stationMap.get(code.toUpperCase());
if (station == null) {
System.out.println("There is no such station present fot this code!");
continue;
}
System.out.println("Station name: "+station.getName());
System.out.println("Station code: "+station.getCode());
System.out.println("Station built date: "+station.getBuiltDate());
}
}
private void readFile() {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("path/to/file")))) {
String line;
while ((line = reader.readLine()) != null) {
String[] strs = line.split("#");
Station station = new Station(strs[0], strs[1], strs[2]);
stationMap.put(station.getCode().toUpperCase(), station);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class Station {
private String name;
private String code;
private String builtDate;
public Station(String name, String code, String builtDate) {
this.name = name;
this.code = code;
this.builtDate = builtDate;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
public String getBuiltDate() {
return builtDate;
}
}
}

Categories