2014-03-25 87 views
0

我有一個.csv文件作爲我的輸入。我需要一個Java程序來爲我讀取這個文件,並根據csv中的日期字段生成一個排序的輸出。輸出文件格式必須是.xmlJava程序讀取.csv並給出排序的.xml輸出

我有以下代碼,雖然我是JAVA新手,請幫助。

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.util.LinkedList; 
import java.util.List; 
import java.util.Map; 
import java.util.TreeMap; 

public class Sort { 
    public static void main(String[] args) throws Exception { 
     BufferedReader reader = new BufferedReader(new FileReader("data1.csv")); 
     Map<String, List<String>> map = new TreeMap<String, List<String>>(); 
     String line = reader.readLine();//read header 
     while ((line = reader.readLine()) != null) { 
      String key = getField(line); 
      List<String> l = map.get(key); 
      if (l == null) { 
       l = new LinkedList<String>(); 
       map.put(key, l); 
      } 
      l.add(line); 

     } 
     reader.close(); 
     FileWriter writer = new FileWriter("sorted_numbers.txt"); 
     writer.write("UserID, Module, Mark\n"); 
     for (List<String> list : map.values()) { 
      for (String val : list) { 
       writer.write(val); 
       writer.write("\n"); 
      } 
     } 
     writer.close(); 
    } 

    private static String getField(String line) { 
     return line.split(",")[0];// extract value you want to sort on 
    } 
} 
+1

什麼是代碼的bug?你可以發佈你的控制檯輸出嗎? –

回答

0

您可以使用csvreader在java中有效地讀取csv文件,而不是BufferedReader

Read a csv file

0
public class ReadCVS { 

public static void main(String[] args) throws ParseException { 

    ReadCVS obj = new ReadCVS(); 
    obj.run(); 

} 

public void run() throws ParseException { 

    String csvFile = "config/one.csv"; 
    BufferedReader br = null; 
    String line = ""; 
    String cvsSplitBy = ","; 

    try { 

     Map<Date, String> maps = new HashMap<Date, String>(); 

     br = new BufferedReader(new FileReader(csvFile)); 
     while ((line = br.readLine()) != null) { 

      String[] country = line.split(cvsSplitBy); 
      SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy"); 
      Date date = sdf.parse(country[2]); 

          //country[2] is date 
      maps.put(date, line); 

     } 
     System.out.println("Unsort Map......"); 
     // printMap(maps); 
     System.out.println("Sorted Map......"); 
     Map<Date, String> treeMap = new TreeMap<Date, String>(maps); 
     printMap(treeMap); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (br != null) { 
      try { 
       br.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    System.out.println("Done"); 
} 

public static void printMap(Map<Date, String> map) { 
    for (Map.Entry entry : map.entrySet()) { 
     System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); 
    } 
} 

}

+0

**示例csv **: 1.0.0.0 \t,1.0.0.255,12:12:14,16777471,AU,澳大利亞 1.0.1.0,1.0.3.255,12:01:12,16778239,CN,中國 – SUBZ