csv中,每一列用
","
分割
//向文件(fileName)中添加一行,这一行的数据是data
public boolean fileAddItem(File fileName,String data) throws IOException {
//打开输出文件流
FileOutputStream fos = new FileOutputStream(fileName,true); // true 表示在后面追加,不加 true 默认表示覆盖原来的数据
OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
//创建字符串缓存
BufferedWriter bw = new BufferedWriter(osw);
// String header = "编号ID,姓名, 身份证号, 查询内容, 查询时间\r\n"; //(文件标题)
// bw.write(header);
StringBuffer str = new StringBuffer();
//添加要写入的数据
str.append(data);
str.append("," + "jone");
str.append("," + "131684198704034255");
str.append("," + "中國繁體");
str.append("," + "2015/6/16" + "\r\n");
//表示写三行
bw.write(str.toString()); // 第一行
bw.write(str.toString()); // 第二行
bw.write(str.toString()); // 第三行
//关闭文件流
bw.flush();
osw.flush();
fos.flush();
return true;
}
完整demo
/**
* @author : ZY
* @Type : test.java
* @date : 3/9/2022 13:43
* @Description : null
*/
import java.io.*;//一次性加载所有 java.io ,后面的可以不用 import
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class test_csv {
public static void main(String args[]){
try {
File fileName = new File("D:\\write.csv");
FileOutputStream fos = new FileOutputStream(fileName,true);
OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
BufferedWriter bw = new BufferedWriter(osw);
String header = "编号ID,姓名, 身份证号, 查询内容, 查询时间\r\n";
bw.write(header);
StringBuffer str = new StringBuffer();
str.append(1);
str.append("," + "jone");
str.append("," + "131684198704034255");
str.append("," + "中國繁體");
str.append("," + "2015/6/16" + "\r\n");
bw.write(str.toString());
bw.write(str.toString());
bw.write(str.toString());
bw.flush();
osw.flush();
fos.flush();
}catch (FileNotFoundException e){
System.out.println("打开文件出错");
}catch (IOException e){
System.out.println("文件读写出错");
}
}
}
版权声明:本文为weixin_47160526原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。