Home >Java >javaTutorial >How to Append Data to a File Using Java's FileWriter?

How to Append Data to a File Using Java's FileWriter?

DDD
DDDOriginal
2024-11-09 21:09:02975browse

How to Append Data to a File Using Java's FileWriter?

Java FileWriter with Append Mode

Problem:

When using Java's FileWriter to write to a file, is there a way to continuously append new data without deleting the existing contents?

Solution:

Yes, you can use the "append" mode in FileWriter to write new data without overwriting previous contents. To enable this mode, pass true as the second argument to the FileWriter constructor:

FileWriter fout = new FileWriter("filename.txt", true);

Here's an updated example:

fout = new FileWriter(
    "Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt", true);
fileout = new PrintWriter(fout,true);
fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");
fileout.close();

By passing true to the FileWriter constructor, you specify that you want to append to the existing file instead of overwriting it.

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