Search code examples
javafilecsvfilewriterprintwriter

PrintWriter appending lines after every execution (Not refreshing the file)


I am pretty new to java, I am writing data to a file. My code looks like this:

File file= new File("model/file.csv");
FileOutputStream writer=null;
try {
    writer = new FileOutputStream(file, true);
} catch (IOException e) {
    e.printStackTrace();
}
PrintWriter pw=null;
pw = new PrintWriter(writer);
try {
    for (int j=0;j< 24; j++)
    pw.format("%.3f%n",MyData);
}
finally {
    pw.close();
} 

Output:

1
2
3
4

But when I run the program for the second time my output file looks like this:

Output:

1
2
3
4
1
2
3
4

Ok I figured that

 writer = new FileOutputStream(file, true);

means that it appends, but I want the file to be refreshed and not contain data from the previous program execution. And also flush doesn't help.


Solution

  • My Suggestion is to use FileWriter like

    Following syntax creates a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

    FileWriter(String fileName, boolean append) 
    

    set boolean to false to indicate you do not want to do the append.

    for example:

       try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", false));) {
    
            for (int i = 0; i < 10; i++) {
                out.println(i);
            }
    
        } catch (IOException e) {
          System.out.println(e);
        }
    

    Read About The Try-With-Resources