Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write data with FileOutputStream without losing old data?

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?

like image 856
iSun Avatar asked Dec 17 '11 12:12

iSun


People also ask

Does FileOutputStream overwrite existing file?

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.

When writing data to a file using a FileOutputStream At what point is the data actually written to the file?

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.

How do you tell FileOutputStream to append data to a file?

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 .

Do I need to close FileOutputStream?

No. It is not require to close other components.


2 Answers

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.

like image 102
Mat Avatar answered Sep 19 '22 14:09

Mat


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); 
like image 43
o_o Avatar answered Sep 22 '22 14:09

o_o