Java Filewriter with Append Mode

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 as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter 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



Leave a reply



Submit