Home > Java > javaTutorial > body text

How to Append Data to a File Using FileOutputStream Without Overwriting Existing Content?

DDD
Release: 2024-11-01 17:47:30
Original
866 people have browsed it

How to Append Data to a File Using FileOutputStream Without Overwriting Existing Content?

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>
Copy after login

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>
Copy after login

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:

  • When using the append mode, it's important to ensure that the file already exists before writing to it. If you try to append to a non-existent file, the FileOutputStream will create a new file instead.
  • The append mode is also available for other OutputStream subclasses, such as PrintStream.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!