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
?
By default, FileOutputStream creates new file or overwrite when we try to write into a file. If you want to append with the existing content, then you have to use “append” flag in the FileOutputStream constructor.
To write data to a Java FileOutputStream you can use its write() method. The write() method takes an int which contains the byte value of the byte to write. Thus, only the lower 8 bit of the passed int actually gets written to the FileOutputStream destination.
Using FileOutputStream FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter . To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .
No. It is not require to close other components.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With