与JavaCSV读CSV文件相对应,JavaCSV也可以用来写数据到CSV文件中。
1.准备工作
(1)第三方包库下载地址:https://sourceforge.net/projects/javacsv
(2)相关文档:http://javacsv.sourceforge.net
2.使用简单的读操作
(1)引入javacsv包相应的类
import com.csvreader.CsvWriter;
(2)创建文件路径
String file = "src/com/xiaoming/csv/test2.csv";
(3)创建CSV写对象
// 创建CSV读对象(文件路径,分隔符,编码格式)
CsvWriter csvWriter = new CsvWriter(file, ',', Charset.forName("UTF-8"));
(4)设置标题
// 设置标题
String[] csvHeaders = { "id", "name"};
csvWriter.writeRecord(csvHeaders);
(5)写入数据
// 写入内容
String[] csvContent1 = { "201804", "小鱼" };
csvWriter.writeRecord(csvContent1);
(6)关闭
// 关闭
csvWriter.close();
测试(demo.java)
package com.test.csv; import com.csvreader.CsvWriter;
import java.io.IOException;
import java.nio.charset.Charset; public class demo {
public static void main(String[] args) {
// 定义一个CSV路径
String file = "src/com/test/csv/test2.csv";
try {
// 创建CSV读对象(文件路径,分隔符,编码格式)
CsvWriter csvWriter = new CsvWriter(file, ',', Charset.forName("UTF-8")); // 设置标题
String[] csvHeaders = { "id", "name"};
csvWriter.writeRecord(csvHeaders); // 写入内容
String[] csvContent1 = { "201804", "小鱼" };
csvWriter.writeRecord(csvContent1); String[] csvContent2 = { "201805", "小红" };
csvWriter.writeRecord(csvContent2); // 关闭
csvWriter.close(); } catch (IOException e) {
e.printStackTrace();
} }
}
生成文件(test2.csv)截图: