0

I am try to write data to a text file. I am using this code:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}

But while the program is running, the file is overwriting the exist data that are already found in the text file. How can i write new data lines to the same text file without overwriting it ? Is there any easy and simple way to write it?

medo0070
  • 411
  • 1
  • 5
  • 21

2 Answers2

3

I think you may use FileWriter(File file, Boolean append)

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

smac89
  • 32,960
  • 13
  • 112
  • 152
btrbt
  • 44
  • 3
3
try (Writer writer = Files.newBufferedWriter(
          Paths.get("filename.txt"), StandardCharsets.UTF_8,
          StandardOpenOption.WRITE,
          StandardOpenOption.APPEND)) {
    writer.write("something");
}

The open options are a varargs list, and default to new file creation.

BTW FileWriter uses the platform encoding, so you where right to not use that class. It is not portable.

Joop Eggen
  • 102,262
  • 7
  • 78
  • 129