0

I am using this method to write to a CSV file. Every time I run my code it removes all previous data from the file instead of adding to it.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        File dir = new File(".");
        String loc = dir.getCanonicalPath() + File.separator + "Code.txt";

        FileWriter fstream = new FileWriter(loc, true);
        BufferedWriter out = new BufferedWriter(fstream);

        out.write("something");
        out.newLine();

        //close buffer writer
        out.close();
    }
}```
  • What you're looking for is how to append to a file. See https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – Mohannad A. Hassan Dec 01 '19 at 01:10

1 Answers1

0

You're better off using java.nio.file.Path, which opens up a lot of utility methods on java.nio.file.Files:

Path path = Path.of("Code.txt"); // Relative to current dir
Files.writeString(path, text, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Where text is the content to append. Files.writeString is from Java 11+. For older versions you can use:

Files.write(path, text.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
boot-and-bonnet
  • 731
  • 2
  • 5
  • 16