I have a text file which contains students information and it has 5 columns: ID, FName, LName, Age, Grade. I want to sort the lines of file by student's grade but it does not work. Here's my method:
public static void sortAndShow() throws Exception {
ArrayList <Student> list = new ArrayList<Student>();
BufferedReader reader = new BufferedReader(new FileReader(originalFile));
String str = reader.readLine();
while (str != null) {
String[] detailsSt = str.split(" ");
int id = Integer.parseInt(detailsSt[0]);
String name = detailsSt[1];
String lastname = detailsSt[2];
int age = Integer.parseInt(detailsSt[3]);
int grade = Integer.parseInt(detailsSt[4]);
list.add(new Student(id, name, lastname, age, grade));
str = reader.readLine();
}
Collections.sort(list, new gradeCompare());
PrintWriter writer = new PrintWriter(new FileWriter(sortedFile, false));
for (Student st : students) {
writer.write((st.getStNum() + " " + st.getFirstName() + " " + st.getLastName() + " " + st.getAge() + " " + st.getGrade() + "\n"));
}
reader.close();
writer.close();
}
And my inner class which do the compare process:
static class gradeCompare implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o2.getGrade() - o1.getGrade();
}
}
My text file before sorting:
101 Jeff King 18 12
102 Tim Woods 17 19
But after sorting it write the same content in the new file:
101 Jeff King 18 12
102 Tim Woods 17 19
I want to after sorting my text file be like (last column is grade):
102 Tim Woods 17 19
101 Jeff King 18 12