简体   繁体   中英

how to write to a new line of CSV file

I am trying to benchmark sorting methods. My writeCSV(String) method writes over the first line every time I call it. Here is my code:

public static void main(String[] args) throws Exception{

    writeCSV("data size (100 times),bubble,insertion,merge,quick");

    sortRandomSet(20);
}

 public static void sortRandomSet(int setSize) throws Exception
{
    .
    .
    .
    writeCSV(setSize+","+bTime+","+mTime+","+iTime+","+qTime);
}
/*******************************************************************************
* writeCSV(course[]) method
* Last edited by Steve Pesce 3/19/2014 for CSci 112
* Writes String to CSV
* 
*/
public static void writeCSV(String line) throws Exception {

    //create new File object 
    java.io.File courseCSV = new java.io.File("benchmark.csv");

    //create PrintWriter object on new File object
    java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV);

    outfile.write(line + "\n");

    outfile.close();
}//end writeCSV(String)

I want writeCSV to start on a new line every time it is called, is this possible to do?

Yeah, right after your call function you can add a string to the first line, have you tried that?

Also, when you create a new file add "a" as an argument which stands for append.

Try using RandomAccessFile

Have a look at this , it should explain how to add things to selected line in a text file

Use java.io.FileWriter instead:

java.io.FileWriter outfile = new java.io.FileWriter("benchmark.csv", true); //true = append
outfile.write(line+"\n");

You could just use the append method. This will append your input to the end of the file.

您应该使用“为此添加方法”

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