Home >Java >javaTutorial >How to Append Data to a File Using FileOutputStream in Java?

How to Append Data to a File Using FileOutputStream in Java?

DDD
DDDOriginal
2024-10-28 22:51:30275browse

How to Append Data to a File Using FileOutputStream in Java?

Appending Data to Files Using FileOutputStream

When using FileOutputStream methods, it's essential to understand that subsequent writes overwrite existing data. However, there exists a solution to append data without obliterating previous content.

Solution

To append data, utilize the FileOutputStream constructor that takes a File and a boolean parameter:

<code class="java">FileOutputStream(File file, boolean append)</code>

Set the boolean parameter to true. This action ensures that the data you write is appended to the end of the file instead of replacing the existing content.

Example

<code class="java">File file = new File("myfile.txt");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write("Appending new data to the file.".getBytes());
fos.close();</code>

By utilizing this approach, the new data will be appended to the end of myfile.txt, preserving the original content.

The above is the detailed content of How to Append Data to a File Using FileOutputStream in Java?. 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