2015-04-29 118 views
1

我以這種格式保存一個txt文件:如何在Java中對文件數據進行排序和重新排列?

806PYZnmNaw4h0wh8fyWDQ 0 0 0 0 0 1 0 
bvu13GyOUwhEjPum2xjiqQ 0 0 0 1 0 0 0 
kDUEcqnK0MrjH9hcYHDKUw 1 0 1 0 0 0 0 
806PYZnmNaw4h0wh8fyWDQ 1 0 1 0 0 0 0 
bvu13GyOUwhEjPum2xjiqQ 0 1 1 1 1 0 0 
tvCT2yT3bLlpU2crUt0zJw 1 0 0 1 0 0 0 
806PYZnmNaw4h0wh8fyWDQ 1 1 1 0 0 0 0 
9Ify25DK87s5_u2EhK0_Rg 0 0 0 1 0 0 0 
bvu13GyOUwhEjPum2xjiqQ 0 1 0 1 0 0 0 
806PYZnmNaw4h0wh8fyWDQ 1 0 0 0 0 0 0 
zk0SnIEa8ju2iK0mW8ccRQ 0 0 0 0 1 0 0 
AMuyuG7KFWJ7RcbT-eLWrQ 0 0 0 1 0 0 0 

現在我需要遍歷這個輸入文件並保存它可以出現多次輸入基於第一編碼值排序,並重新排列輸出文件文件?對於例如在這個示例文件中,我在隨機地方有不止一次806PYZnmNaw4h0wh8fyWDQ

這是迄今爲止我嘗試過: private static final String Path =「newuserfeature.txt」;

public static void main(String[] args) { 
    List<String> list = new ArrayList<String>(); 
    List<String> uniquelist = new ArrayList<String>(); 
    try { 

     Scanner unique = new Scanner(new FileReader(Path)); 

     while (unique.hasNextLine()) { 
      String userUnique = unique.nextLine(); 
      uniquelist.add(userUnique); 
     } 

     Iterator<String> it = uniquelist.iterator(); 

     while (it.hasNext()) { 
      String user = it.next(); 
      int a = 0; 
      int b = 0; 
      int c = 0; 
      int d = 0; 
      int e = 0; 
      int f = 0; 
      int g = 0; 

      Iterator<String> it2 = list.iterator(); 
      while (it2.hasNext()) { 
       String[] y = it2.next().toString().split(" "); 
       if (user.equalsIgnoreCase(y[0])) { 
        int a1 = Integer.parseInt(y[1]); 
        int b1 = Integer.parseInt(y[2]); 
        int c1 = Integer.parseInt(y[3]); 
        int d1 = Integer.parseInt(y[4]); 
        int e1 = Integer.parseInt(y[5]); 
        int f1 = Integer.parseInt(y[6]); 
        int g1 = Integer.parseInt(y[7]); 

        if (a1 == 1) { 
         a = a1; 
        } 
        if (b1 == 1) { 
         b = b1; 
        } 
        if (c1 == 1) { 
         c = c1; 
        } 
        if (d1 == 1) { 
         d = d1; 
        } 
        if (e1 == 1) { 
         e = e1; 
        } 
        if (f1 == 1) { 
         f = f1; 
        } 

       } 

      } 
      System.out.println(user + " " + a + " " + b + " " + c + " " + d 
        + " " + e + " " + f + " " + g + "\n"); 
     } 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 
+0

我試過使用兩個列表並根據第一個元素比較每個其他人嗎? – Milson

+0

「重新排列」是什麼意思?你在做「串」排序嗎? – morgano

+0

是的,根據輸入文件中的第一個元素值進行排序。 – Milson

回答

2

如果只是排序由這恰好是一個字符串的第一個字段的線,你可以你只是做:

Path oldFile = Paths.get("/path/to/my/file"); 
Path newFile = Paths.get("/path/to/my/newFile"); 

List<String> lines = Files.readAllLines(oldFile); 
Collections.sort(lines); 
Files.write(newFile, lines); 

其中:

1:加載的所有線字符串列表
2:按字符串排序(這就是你想在一天結束時)
3:將行存儲在另一個文件中

由於您正在按第一個字段進行字符串排序,因此不需要將每行分解爲其列。

相關問題