2014-02-07 154 views
2

我想讀取位於一個文件夾中的所有CSV文件,然後按名稱爲「名稱」的字段進行排序。Java按字段排序CSV文件

這樣做的最佳方法是什麼?

輸入文件的例子:

File1:- 

address,name,custnum 
190 vikign,Cname,123455 
1555 oakbroo,BName,123455 
1234 sprint st,EName,123455 

File2:- 

address,name,custnum 
190 sprint,Wname,123455 
1555 windy hill,AName,123455 
1234 sprint st,BName,123455 

One OutPut File like:- 

address,name,custnum 
1555 windy hill,AName,123455 
1555 oakbroo,BName,123455 
1234 sprint st,BName,123455 
190 vikign,Cname,123455 
1234 sprint st,EName,123455 
190 sprint,Wname,123455 

到目前爲止我的代碼:

import java.io.BufferedReader; 
    import java.io.BufferedWriter; 
    import java.io.File; 
    import java.io.FileNotFoundException; 
    import java.io.FileReader; 
    import java.io.FileWriter; 
    import java.io.IOException; 
    import java.util.Arrays; 
    import java.util.HashMap; 
    import java.util.regex.Pattern; 

    public class MoniLetterOwnmanSorting1 { 

     /** 
     * @param args 
     */ 

     public static void delFileFromDir(String dirPath) { 
      File dir = new File(dirPath); 
      if (dir.listFiles() == null) 
       return; 
      for (File file : dir.listFiles()) { 
       if (!file.isDirectory()) 
        file.delete(); 
      } 
     } 

     public static void main(String[] args) throws IOException { 
      // TODO Auto-generated method stub 

      BufferedReader br = null; 
      BufferedWriter bfAll = null; 

      File folder = new File("OwnmanFileIn"); 
      File[] BFFile = folder.listFiles(); 

      String count = "OwnmanFileOut\\" + "OwnmanFileSort.csv"; 
      bfAll = new BufferedWriter(new FileWriter(count)); 

      for (File file : BFFile) { 

       br = new BufferedReader(new FileReader(file)); 

       String line; 
       line = br.readLine(); 

       while((line = br.readLine()) != null) { 

        String[] actionID = line.split("\\,"); 

        String name= actionID[1].replace("\"", ""); 

        //PLEASE HELP ME!! 

       } 

      } 

     } 

    } 

回答

0

例如你可以用每一行

public class AddressLine implements Comparable<AddressLine> {
String address,name;
public AddressLine(String name ... //Constructor
public int compareTo(AddressLine another){
return name.compareTo(another.name);}

下一頁添加所有行

ArrayList<AddressLine> list; 

並使用

Collections.sort(list) 
+0

對不起,先生,我不明白,這辦法可以做到這一點,數組名場比那種? – user3187463

+0

非常感謝您的幫助,我明白了,謝謝! – user3187463

1
step 1 : create a class , like a bean class having fields as the columns of the CSV 

step 2 : write getters and setters for when you need them 

step 3 : read all your files and store every row in an object of the bean class 

step 4 : create an arraylist of the bean class type and store all the bean objects i the arraylist 

step 5 : write a comparator method for your bean class and sort it the way you want it 
+0

非常感謝您的幫助,我明白了,謝謝! – user3187463

+0

不客氣 –