Java FileWriter with append mode
Pass true
as a second argument to FileWriter
to turn on "append" mode.
fout = new FileWriter("filename.txt", true);
FileWriter usage reference
How to append text to an existing file in Java?
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
Java 7+
For a one-time task, the Files class makes this easy:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException
if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE
and APPEND
options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter
is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
- The second parameter to the
FileWriter
constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.) - Using a
BufferedWriter
is recommended for an expensive writer (such asFileWriter
). - Using a
PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
. - But the
BufferedWriter
andPrintWriter
wrappers are not strictly necessary.
Older Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
Filewriter will not append text to newly created file
Pass true as a second argument to FileWriter to turn on "append" mode (in the first FileWriter you have created).
Also, you should create the variable FileWriter
, and close it after appending "List:", as you leave the scope of that variable.
So, I would edit the code as following:
File hi = new File("hi.txt");
try {
if (!hi.exists()) {
System.out.printf("\nCreating 'hi.txt'.");
hi.createNewFile();
String hello = "List:";
FileWriter writer = new FileWriter(hi, true);
writer.append(hello);
writer.close();
} else {
System.out.printf("\nWriting to 'hi.txt'");
}
FileWriter writeHere = new FileWriter(hi, true);
String uling = "hi";
writeHere.append(uling);
writeHere.close();
}
//error catching
catch (IOException e) {
System.out.printf("\nError. Check the file 'hi.txt'.");
}
NOTICE: Modifications at lines 7-9.
http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
Java Append input to File
To append content to an existing file, open file writer in append mode by passing second argument as true.
fw = new FileWriter(FILENAME,true);
bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.println(String.valueOf(string));
out.println(op);
FileWriter won't append new lines
When writing the file, you need to include both a newline and a linefeed character.
So, in your toString()
method, where you add the "\n"
newline, instead add both a linefeed and newline: "\r\n"
FileWriter only writes first line (Append Mode enabled, Java)
You have this structure:
while (true) {
try {
// Code which writes one line
} finallly {
out.close();
}
}
In other words, you're closing the output after the first line, but continuing to do work. That's not going to reopen the output...
You should really use a try-with-resource block for the whole thing, with the while loop entirely inside it, so that you don't close the writer until your whole loop has finished. (Admittedly at the moment it can only finish due to an exception... you might want to add some non-exceptional way of stopping the loop...)
How to switch on and off file writer appending?
Since your program knows whether or not to append inside the conditional, you could create your writer inside the conditional, too:
if (headers.length != 0) {
writer = new FileWriter(sFileName); // Do not append
// here is the point which will not happen twice, just if i re-run the program
writer.append(headers);
writer.append('\n');
} else {
writer = new FileWriter(sFileName, true); // Append
// write values to the file
writer.append(values.toString());
}
writer.flush();
writer.close();
Related Topics
Java Random Always Returns the Same Number When I Set the Seed
Effective Gif/Image Color Quantization
Simple Popup Java Form with at Least Two Fields
Swingpropertychangesupport to Dynamically Update Jtextarea
Abstracttablemodel Gui Display Issue
Maven Modules + Building a Single Specific Module
Handling Exceptions from Java Executorservice Tasks
What Is the Meaning of the Cascadetype.All for a @Manytoone JPA Association
Nullpointerexception in Collectors.Tomap with Null Entry Values
Classpath Resource Not Found When Running as Jar
How to Get Parameters from the Url with Jsp
Explicit Casting from Super Class to Subclass
Why to Use Interfaces, Multiple Inheritance VS Interfaces, Benefits of Interfaces
What Is the Use of Interface Constants
What Does Java Option -Xmx Stand For
Returning Null as an Int Permitted with Ternary Operator But Not If Statement