java - 写入 CSV 文件时如何跳过第一行
问题描述
所以我使用 2 种方法写入 CSV 文件,都使用 PrintWriter 和 StringBuilder。
方法一只写入CSV文件的主题,即在CSV文件的第一行写入一些东西。
第二种方法将我需要的一些其他数据写入同一个 CSV 文件的其余部分。
我的问题是我可以做些什么来跳过 CSV 文件的第一行,这样当我用第二种方法写入它时,我最终不会覆盖我在第一种方法中写的内容。
public void writeData(String filename, ArrayList<ITemperature> theWeatherList) {
try(PrintWriter pw = new PrintWriter(filename)){
StringBuilder sb = new StringBuilder();
sb.append("\n");
for(int i = 0; i < theWeatherList.size(); i++) {
// Appends current ITemperature object to string builder
String[] temp = asString(theWeatherList.get(i)).split(",");
sb.append(temp[0]);
sb.append(",");
sb.append(temp[1]);
sb.append(",");
sb.append(temp[2]);
sb.append(",");
sb.append(temp[3]);
sb.append(",");
sb.append(temp[4]);
sb.append("\n");
}
// Writes into file
pw.write(sb.toString());
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("Data written to file.");
}
解决方案
我不知道您的代码如何,但请尝试这样做。
fw = new FileWriter("file.csv", true);
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
pw.println("Line one");
pw.println("Line two");
pw.println("Line three");
推荐阅读
- c++ - 在 TIBCO DataSynapse GridServer 中的 C++ 客户端/服务器之间传输字节数组
- amazon-web-services - AWS Elastic Beanstalk - 运行 powershell 命令未在 .ebextensions 上执行
- c# - 如何使用其名称获取窗口服务的 pid 并检查进程是否在任务管理器中运行?使用 C#
- laravel - 推送到会话会覆盖数据?
- php - 如何在 WordPress 中创建自定义可拖动小部件
- css - 如何在图像中使用 CSS 蒙版?
- c# - itext7 使用来自用户商店的证书签署 pdf,没有“可导出”属性
- python - 无法从转换器导入 BertModel
- c - 外部全局变量示例 - 错误
- linux - 一般保护调试