Java中csv文件的写与读
依赖配置
- pom.xml文件中,配置javacsv工具包
<dependency> <groupId>net.sourceforge.javacsv</groupId> <artifactId>javacsv</artifactId> <version>2.0</version> </dependency>
写csv文件
- 简单示例写函数
public static void writeCsv(String filePath) { try { File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } // 创建CSV写对象 CsvWriter csvWriter = new CsvWriter(filePath, ',', Charset.forName("GBK")); // 写表头 String[] headers = {"content"}; csvWriter.writeRecord(headers); //写内容 String[] content1 = {"hello"}; String[] content2 = {"world"}; csvWriter.writeRecord(content1); csvWriter.writeRecord(content2); csvWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
读取csv文件
- 简单实例读函数
public static void readScv(String filePath) { File file = new File(filePath); if (!file.exists()) { System.out.println("文件不存在!"); return; } try { // 创建CSV读对象 CsvReader csvReader = new CsvReader(filePath, ',', Charset.forName("GBK")); // 读表头 csvReader.readHeaders(); while (csvReader.readRecord()) { // 读取一行数据 System.out.println(csvReader.getRawRecord()); } } catch (IOException e) { e.printStackTrace(); } }
在实践中暂时遇到的问题
- 当数字过长会变成科学计数法
- 如:140108199212301237变成140108199212300000【解决方案:制表符和true的配合使用(先留个思考,在下面的函数中会有体现)】
- 编码问题
- 使用UTF-8读文件时,存在乱码问题【解决方案:读写都采用使用GBK编码】
函数升级改造
Csv文件写函数
- 封装的写函数
public static void read(String filePath,String column_name) { File file = new File(filePath); if (!file.exists()) { System.out.println("文件不存在!"); return; } try { // 创建CSV读对象 CsvReader csvReader = new CsvReader(filePath, ',', Charset.forName("GBK")); // 读表头 csvReader.readHeaders(); while (csvReader.readRecord()) { // 读这行的某一列 System.out.println(csvReader.get(column_name)); } } catch (IOException e) { e.printStackTrace(); } }
Csv文件度函数
- 封装的度函数
public static void write(String filePath, String[] headers, List<String[]> datas) { try { File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } // 创建CSV写对象 CsvWriter csvWriter = new CsvWriter(filePath, ',', Charset.forName("GBK")); // 写表头 csvWriter.writeRecord(headers); if (datas != null && datas.size() > 0) { for (String[] temp : datas) { for (int i = 0; i < temp.length; i++) { //防止数字过长出现科学计数法的问题【\t和true来解决】 temp[i] = temp[i] + "\t"; } csvWriter.writeRecord(temp, true); } } csvWriter.close(); } catch (IOException e) { e.printStackTrace(); } }