首页 > 解决方案 > 写入 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.");

}

标签: javacsv

解决方案


我不知道您的代码如何,但请尝试这样做。

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");

推荐阅读