2017-02-13 83 views
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){ 
     } 
    } 

} 
+2

's1 = lines.get(0); s2 = lines.get(1);' - 你在幹什麼? – user2357112

+0

如果您刪除了@ user2357112已識別的兩行,那麼解決您的問題將是一個好開始。 –

+0

傳遞給'Collections.sort'的比較器已經傳入要比較的字符串中(來自您的ArrayList ),因此您不需要手動設置它們。此外,你實際上覆蓋了傳遞給比較器的正確值。 –

回答

1

I'ava試圖用 「比較」。對於我的簡單的源文件是如下

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] 

上排序第三場!

+0

謝謝你「親切」地回答我的問題。這個選項適用於我。 – Dante