1.使用IO流读写csv文件
1) 读
BufferedReader br = new BufferedReader(new FileReader("acsv.csv")); String line = null; while ((line = br.readLine()) != null){ String[] strs = line.split(","); System.out.println(Arrays.toString(strs)); }
2) 写
File file = new File("acsva.csv"); if (!file.exists()) { file.createNewFile(); } BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(""李四"" + "," + ""1988"" + "," + ""1992""); bw.newLine();
2.使用CsvReader、CsvWriter读写csv文件
1) 读
// 用来保存数据 ArrayList<String[]> csvList = new ArrayList<String[]>(); CsvReader reader = new CsvReader("abc.csv", ',', Charset.forName("utf-8")); // 跳过表头 如果需要表头的话,不要写这句。 reader.readHeaders(); // 逐行读入除表头的数据 while (reader.readRecord()) { csvList.add(reader.getValues()); } for (int row = 0; row < csvList.size(); row++) { String cell = csvList.get(row)[0]; // 取得第row行第0列的数据 System.out.println(cell); }
2) 写
CsvWriter wr = new CsvWriter("abc.csv", ',', Charset.forName("utf-8")); String[] contents = { "告警信息", "非法操作", "没有权限", "操作失败" }; // 写入一行数据 wr.writeRecord(contents);