Create a text file if it doesn't exist and append to it if it does using Java BufferedWriter

Alan K picture Alan K · Aug 15, 2015 · Viewed 11.4k times · Source

This is probably ridiculously simple for gun Java programmers, yet the fact that I (a relative newbie to Java) couldn't find a simple, straightforward example of how to do it means that I'm going to use the self-answer option to hopefully prevent others going through similar frustration.

I needed to output error information to a simple text file. These actions would be infrequent and small (and sometimes not needed at all) so there is no point keeping a stream open for the file; the file is opened, written to and closed in the one action.

Unlike other "append" questions that I've come across, this one requires that the file be created on the first call to the method in that run of the Java application. The file will not exist before that.

The original code was:

            Path pathOfLog = Paths.get(gsOutputPathUsed + gsOutputFileName);
            Charset charSetOfLog = Charset.forName("US-ASCII");
            bwOfLog = Files.newBufferedWriter(pathOfLog, charSetOfLog);
            bwOfLog.append(stringToWrite, 0, stringToWrite.length());
            iReturn = stringToWrite.length();
            bwOfLog.newLine();
            bwOfLog.close();

The variables starting with gs are pre-populated string variables showing the output location, and stringToWrite is an argument which is passed in.

So the .append method should be enough to show that I wanted to append content, right?

But it isn't; each time the procedure was called the file was left containing only the string of the most recent call.

Answer

Alan K picture Alan K · Aug 15, 2015

The answer is that you also need to specify open options when calling the newBufferedWriter method. What gets you is the default arguments as specified in the documentation:

If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present.

Specifically, it's TRUNCATE_EXISTING that causes the problem:

If the file already exists and it is opened for WRITE access, then its length is truncated to 0.

The solution, then, is to change

bwOfLog = Files.newBufferedWriter(pathOfLog, charSetOfLog);

to

bwOfLog = Files.newBufferedWriter(pathOfLog, charSetOfLog,StandardOpenOption.CREATE, StandardOpenOption.APPEND);

Probably obvious to long time Java coders, less so to new ones. Hopefully this will help someone avoid a bit of head banging.