我正在尝试对文本文件进行排序,该文件由制表符分隔并尝试按第三个字段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){
}
}
}
答案 0 :(得分:1)
我尝试使用&#34;比较器&#34;。为简单起见,我的源文件如下
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]
按第三栏排序!