Straight to the point. I believe it's very easy to solve, but somehow I'm stuck. I have a class Uploader which is called from main class. This class streams a txt file with a student list and prints it out. However, I can't find a solution, how to store this txt file in the ArrayList and use it in other classes. File is sorted based on the Student class which overrides toString method to get the print output. I tried to use collect(collectors.toList()) method, but didn't work. I guess that I'm missing something obvious. Could anyone suggest anything ? Thanks.
Here is my code for Student class:
public class Student extends People {
private String collegeName;
private String studentType;
private final String studentID;
public Student(String firstName, String secondName, String telNo, String collegeName, String studentID, String studentType ) {
super(firstName, secondName, telNo);
this.studentID = studentID;
this.collegeName = collegeName;
this.studentType = studentType;
}
public String getStudentI() {
String studentDet = getPeople() + collegeName + " " + studentType + " Student";
return studentDet;
}
@Override
public String toString() {
return "Student [name= " + firstName + ", second Name= " + secondName + " Telephone number= " + telNo + "college name= " + collegeName + " Student ID " + studentID + " Student Type= " + studentType + "]";
}
}
And here is Uploader Class:
public class Uploader {
private String fileName = null;
private void getPath() {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
setFileName(f.getAbsolutePath());
System.out.println(getFileName());
}
void Uploader() {
getPath();
Path path = Paths.get(getFileName());
try (Stream<String> lines = Files.lines(path)) {
lines
.flatMap(Uploader::lineToPerson)
.forEach(System.out::println);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static Stream<Student> lineToPerson(String line) {
try {
String[] elements = line.split(",");
String firstName = elements[0];
String secondName = elements[1];
String telNo = elements[2];
String collegeName = elements[3];
String studentID = elements[4];
String studentType = elements[5];
Student p = new Student(firstName, secondName, telNo, collegeName, studentID, studentType);
return Stream.of(p);
} catch (Exception e) {
}
return Stream.empty();
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}