2014-08-28 24 views
-6

csv文件2級排序我的文件是這樣的:如何實現在使用Java

55 44 1 
55 33 0 
55 77 2 
55 88 3 
44 333 1 
44 444 0 
11 6 1 
11 3 3 
11 5 2 

我需要重新排序,如:

11 6 1 
11 5 2 
11 3 3 
44 444 0 
44 333 1 
55 33 0 
55 44 1 
55 77 2 
55 88 3 

誰能幫助我實現這一目標?

+4

請提供一些努力,最好是代碼。 – 2014-08-28 10:47:25

+1

我想如果你在谷歌2搜索可以在15-30分鐘內找到你的解決方案。 「使用Java從文件讀取」和「使用Java重新排列數組/列表」 – AlvaroAV 2014-08-28 10:48:43

回答

1

當它只是一個小文件,你可以解決它像這樣

  • 讀取所有行到一個列表
  • 使用自己的比較實現自己的Comparator
  • 排序列表

這個例子只是一個PoC。任何不需要顯示該原則的內容都被省略了。

import java.io.IOException; 
import java.nio.charset.Charset; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 

/** 
* @author SubOptimal 
*/ 
public class Main { 

    public static Comparator<String> getComparator() { 
     return new Comparator<String>() { 
      @Override 
      public int compare(String o1, String o2) { 
       // split the lines to compare by whitespaces 
       String[] columns1 = o1.split("\\s+"); 
       String[] columns2 = o2.split("\\s+"); 
       // compare first column 
       if (columns1[0].compareTo(columns2[0]) != 0) { 
        return columns1[0].compareTo(columns2[0]); 
       } 
       // compare third column 
       if (columns1[2].compareTo(columns2[2]) != 0) { 
        return columns1[2].compareTo(columns2[2]); 
       } 
       // both lines have equal 
       return 0; 
      } 
     }; 
    } 

    public static void main(String[] args) throws IOException { 
     final Path path = Paths.get("input.csv"); 
     // read all lines into a list of String 
     List<String> lines = Files.readAllLines(path, DEFAULT_CHARSET); 
     // sort the list using your own comparator 
     Collections.sort(lines, getComparator()); 
     // output the sorted list 
     for (String line : lines) { 
      System.out.println(line); 
     } 
    } 

    private static final Charset DEFAULT_CHARSET = Charset.defaultCharset(); 
} 
+1

非常感謝... – 2014-08-28 13:41:55