日期:2014-05-20 浏览次数:20903 次
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Random; public class CSV2 { public static void main(String[] args) throws IOException { long t0 = System.currentTimeMillis(); Random ran = new Random(); String line = System.getProperty("line.separator"); File file = new File("random.csv"); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); for(int i=1; i<=50000;i++) { int num = ran.nextInt(99999) + 1; bw.write("\""); bw.write(String.format("%05d",num)); bw.write("\""); if(i%5!=0) { bw.write(","); }else{ bw.write(line); } } bw.close(); long time = System.currentTimeMillis() - t0; System.out.printf("耗时:%d(ms)%n", time); } }
------解决方案--------------------
呵呵,好了,第一个也完成了。
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class CSVSort { public static void main(String[] args) { long t0 = System.currentTimeMillis(); if (args.length != 3) { System.out.println("错误[1]:参数不正确!"); System.out.println("使用方法: CSVSort <源文件名> <新文件名> <排序列号>"); System.exit(1); } File file1 = new File(args[0]); if (!file1.exists()) { System.out.println("错误[2]: " + args[0] + " 文件没有找到!"); System.exit(2); } File file2 = new File(args[1]); if (file2.exists()) { System.out.println("错误[3]: " + args[1] + " 文件已经存在!"); System.exit(3); } List<String> list = readFile(file1); int tmp = list.get(0).split(",").length; // 计算总共的列数 int col = Integer.parseInt(args[2]); if (col < 1 || col > tmp) { list.clear(); System.out.println("错误[4]: 列号不正确!"); System.exit(4); } sort(list, col); writeFile(file2, list); long time = System.currentTimeMillis() - t0; System.out.printf("耗时:%d(ms)%n", time); } public static List<String> readFile(File file) { BufferedReader br = null; List<String> list = new ArrayList<String>(); try { br = new BufferedReader(new FileReader(file)); String str = ""; while ((str = br.readLine()) != null) { str = str.trim(); if (str.length() > 0) { list.add(str); } } br.close(); } catch (IOException e) { e.printStackTrace(); } return list; } public static void writeFile(File file, List<String> list) { BufferedWriter bw = null; try { String line = System.getProperty("line.separator"); bw = new BufferedWriter(new FileWriter(file)); for (String str : list) { bw.write(str); bw.write(line); } bw.close(); } catch (IOException e) { e.printStackTrace(); } } public static void sort(List<String> list, final int column) { Collections.sort(list, new Comparator<String>() { public int compare(String str1, String str2) { String[] str1s = str1.split(","); String[] str2s = str2.split(","); return str1s[column - 1].compareTo(str2s[column - 1]); } }); } }