How to Write Data Using FileOutputStream Without Overwriting Existing Content
Preserving existing data when writing to files using FileOutputStream is a common concern. By default, FileOutputStream overwrites the file if it already exists. Fortunately, there's a way to avoid this and append new data instead.
Solution:
The key is to use the FileOutputStream constructor that takes two arguments:
<code class="java">FileOutputStream(File file, boolean append)</code>
Here, the boolean parameter specifies whether to append (true) or overwrite (false). By setting append to true, the data you write will be added to the end of the file, without deleting the existing content.
Example:
<code class="java">File file = new File("my_file.txt"); FileOutputStream fos = new FileOutputStream(file, true); fos.write("Hello world!".getBytes());</code>
In this example, the data "Hello world!" will be appended to the file named "my_file.txt". If the file already exists, its existing contents will not be lost.
Additional Notes:
The above is the detailed content of How to Append Data to a File Using FileOutputStream Without Overwriting Existing Content?. For more information, please follow other related articles on the PHP Chinese website!