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
Release: 2024-10-28 22:51:30
Original
337 people have browsed it

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

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

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!

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