简体   繁体   中英

how do I skip the first line when writing to a CSV file

So I'm using 2 methods to write to a CSV file, both using a PrintWriter and StringBuilder.

Method one only writes the subject of the CSV file, that is, it writes something into the first line of the CSV file.

The second method writes some other data I need into the rest of the same CSV file.

My question is what I can do to skip the first line of the CSV file, so that when I write into it in my second method, I don't end up overwriting what I wrote in the first method.


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

}

I don't know how is your code, but try to do it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM