我正在尝试对由制表符分隔的文本文件进行排序,并尝试按第三个字段 className 进行排序。然后我将把它显示在表格中。我写了以下部分,但排序不正确。关于我哪里出错了有什么想法吗?
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){
}
}
}
最佳答案
我尝试使用“比较器”。为简单起见,我的源文件如下
pippo;pluto;paperino
casa;terra;cortile
primo;secondo;terzo
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.split(";")[2].compareTo(o2.split(";")[2]);
}
};
lines.sort(comparator);
最终输出
[casa;terra;cortile, pippo;pluto;paperino, primo;secondo;terzo]
按第三个字段排序!
关于java - 使用 Collections.sort 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42210808/