Home >Java >javaTutorial >How to Append Data to a File Using FileOutputStream Without Overwriting Existing Content?

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

DDD
DDDOriginal
2024-11-01 17:47:30967browse

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>

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:

  • 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!

Statement:
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