我有一个.csv文件作为输入。我需要一个Java程序来为我读取这个文件,并根据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
}
}
答案 0 :(得分:0)
您可以在java中使用csvreader
来有效地阅读csv
文件,而不是BufferedReader
答案 1 :(得分: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());
}
}
}