86

If you work with FileOutputStream methods, each time you write your file through this methods you've been lost your old data. Is it possible to write file without losing your old data via FileOutputStream?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
iSun
  • 1,526
  • 6
  • 26
  • 53
  • 1
    If you are wondering how you could have worked this out for yourself, you could have read the Javadoc. http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html – Peter Lawrey Dec 17 '11 at 16:21
  • [OutputStreamWriter is used instead of FileOutputStream][1] [1]: http://stackoverflow.com/questions/23320070/appending-a-string-to-an-existing-file-using-outputstreamwriter/23320195?noredirect=1#comment35707473_23320195 – sourabh Apr 27 '14 at 10:41
  • 2
    @PeterLawrey to learn by ourself, one usually simply ask internet. And SO is the 1st result before the java doc :-) – Juh_ Dec 30 '17 at 22:12

2 Answers2

156

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

Mat
  • 188,820
  • 38
  • 367
  • 383
20

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
o_o
  • 496
  • 2
  • 9