I'm making a student system with console based java. I'm trying to load a text file's content to an ArrayList and later on search with a student registration number and list down his/her name and program. I'm having a hard time loading the text file contents in an ArrayList so that I can retrieve them later on as objects.

I have made a search function that works perfectly on an Arraylist (Since when entering a new record I am putting them in ArrayList and they can be searched until the program is not shut)

This is the approach I am using trying to load the text file in an ArrayList:

try {

            ArrayList<NewStudent> student = new ArrayList<>(); 
             BufferedReader inFile = new BufferedReader (new FileReader 
                       ("Test.txt"));
            String inputLine;

            while ((inputLine = inFile.readLine())!=null) { 

                NewStudent ns = new NewStudent();
                String[] studentVars = inputLine.split(":"); 
                ns.setName(studentVars[0]);

        student.add(ns);


            }
            System.out.print(student);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

This is my approach in searching and this works like a charm

public Student Search(String ID, ArrayList<Student> StudentList)
    {
        Student myStudent = new Student();

        for(int i=0 ; i<StudentList.size() ; i++)
        {
            if(StudentList.get(i).getID().equals(ID))
            {
                myStudent.setID(StudentList.get(i).getID());
                myStudent.setName(StudentList.get(i).getName());
                myStudent.setProgram(StudentList.get(i).getProgram());

                return myStudent;
            }
        }
        return null;
    }

**When it prints, it prints this:**
[com.Student.NewStudent@615e7597, com.Student.NewStudent@7a3e72, com.Student.NewStudent@5999ae9c, com.Student.NewStudent@7896b1b8, com.Student.NewStudent@6d6de4e1, com.Student.NewStudent@49cda7e7, com.Student.NewStudent@5cca548b]

** And if I use a different approach that is:**

  BufferedReader inFile = new BufferedReader (new FileReader 
                       ("Student.txt"));
               ArrayList<String> arrayList = new ArrayList<>();
               String inputLine;
            while ( (inputLine = inFile.readLine() ) != null) {
                String[] stud = inputLine.split(":"); 
                arrayList.add(stud[0]); \\if I add stud[1] it gives null pointer exception


            }
          System.out.println(arrayList);

This doesn't return as separate objects. it shows one straight line

if it prints something like this: om.Student.NewStudent@49cda7e7
that just means you didn't override the toString method, so it uses the default one provided by the Object class.

add

public String toString(){
  return this.name;
}

to the NewStudent class

it's being printed in a list, because you don't print each element, but you print the list instead

I'm trying to get better with the new Java 8 Streams API and this seems like a good candidate. Here goes:

 public static void main(String[] args) {
    final ArrayList<Student> studentList = new ArrayList<>();
    try {
       Stream<String> lines = Files.lines(Paths.get("studentTest.txt"));
       lines.forEach((String t) -> {
          String[] parse = t.split(":");
          if(parse.length<2) return;
          studentList.add(new Student(parse[0], parse[1]));
       });
    } catch (IOException ex) {
       System.out.println("Unable to open student file." + ex.toString());
    }
    System.out.println(studentList);
 }

Less code and more readable. The text file I used is this:
John Smith:78231
Joe DeStudent:78332
Alice DatGirl:67323
Karen Kenderson:45444

Nice example.
You can push the Stream usage a bit further, depending on the overall requirements, along the lines of:

Files.lines(Paths.get("studentTest.txt"))
.map(line -> line.split(":"))
.filter(parse -> parse.length == 2)
.map (parse -> new Student(parse[0], parse[1]))
.collect(Collectors.toList());

Edited 2 Years Ago by JamesCherrill

Comments
Fantastic! I knew it could be done in one line.
This article has been dead for over six months. Start a new discussion instead.