How to add recorded data to a file?

I am a new developer in android.i would like to write some content to a file, I used a method to write to a file as follows

public void writeFile(String path,String text){ try{ Writer output = null; File file = new File(path); output = new BufferedWriter(new FileWriter(file)); output.write(text); output.close(); System.out.println("Your file has been written"); } catch (Exception e) { e.printStackTrace(); } 

here I go through the file path and text for write.if I use this way, I can write data, but previous data is lost.

How can I add or paste the last text into a file without losing the previous text?

Thanks in advance

+6
source share
2 answers

Try it. Change this line ...

 output = new BufferedWriter(new FileWriter(file)); 

to

 output = new BufferedWriter(new FileWriter(file, true)); 

True indicates that you want to add do not overwrite

+10
source

Take a look here and try:

 new FileWriter(file, true); 

a boolean value indicates whether to add to an existing file.

+3
source

Source: https://habr.com/ru/post/890895/


All Articles