0
比較我想排序一個文本文件,這是由製表符分隔,並嘗試按第三個字段,className排序。然後我將把它顯示在一個表格中。我寫了下面的部分,但它沒有正確排序。任何想法,我要去哪裏錯了?使用Collections.sort
public void sortFile(){
BufferedReader reader = null;
BufferedWriter writer = null;
//Create an ArrayList object to hold the lines of input file
ArrayList<String> lines = new ArrayList<>();
try{
//Creating BufferedReader object to read the input file
reader = new BufferedReader(new FileReader("pupilInfo.txt"));
//Reading all the lines of input file one by one and adding them into ArrayList
String currentLine = reader.readLine();
while (currentLine != null){
lines.add(currentLine);
currentLine = reader.readLine();
}
Collections.sort(lines, (String s1, String s2) -> {
s1 = lines.get(0);
s2 = lines.get(1);
String [] line1 = s1.split("\t");
String [] line2 = s2.split("\t");
String classNameLine1 = line1[2];
String classNameLine2 = line2[2];
System.out.println("classname1=" + classNameLine1);
System.out.println("classname2=" + classNameLine2);
int sComp = classNameLine1.compareTo(classNameLine2);
return sComp;
});
//Creating BufferedWriter object to write into output temp file
writer = new BufferedWriter(new FileWriter("pupilSortTemp.txt"));
//Writing sorted lines into output file
for (String line : lines){
writer.write(line);
writer.newLine();
}
}catch (IOException e){
}
finally{
//Closing the resources
try{
if (reader != null){
reader.close();
}
if(writer != null){
writer.close();
}
}catch (IOException e){
}
}
}
's1 = lines.get(0); s2 = lines.get(1);' - 你在幹什麼? – user2357112
如果您刪除了@ user2357112已識別的兩行,那麼解決您的問題將是一個好開始。 –
傳遞給'Collections.sort'的比較器已經傳入要比較的字符串中(來自您的ArrayList),因此您不需要手動設置它們。此外,你實際上覆蓋了傳遞給比較器的正確值。 –