0

Im trying to add multiple strings to a file.

FileWriter myWriter = new FileWriter("cache.txt");
BufferedWriter bw=new BufferedWriter(myWriter);
bw.write(marker);
bw.newLine();
bw.close();

But whenever I write a new String it keeps overriding. So I only have one string in my file. How would I make it add a new line to the file.

Here is an example What should happen. file(cache.txt):

fd174d5b4bbc85295a649f9d70a4adf4

9b854017b04d62732ac00f2ee8007968

...

What happens for me file(cache.txt):

9b854017b04d62732ac00f2ee8007968(last entry)

DedS3t
  • 183
  • 1
  • 7

2 Answers2

0

Use the "append" flag to the FileWriter constructor:

FileWriter myWriter = new FileWriter("cache.txt", true);

Otherwise the file will be reset to the beginning each time it is opened.

AbbeGijly
  • 1,191
  • 1
  • 4
  • 5
0

Because that's what BufferedWriter's .write is supposed to do.

If the file doesn't exists, create and write to it. If the file exists, truncate (remove all content) and write to it

To append, use this:

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("text");
    out.close();
} catch (IOException e) {
    //exception handling
}
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43