Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 717
Alan K Avatar asked Aug 15 '15 21:08

Alan K


People also ask

How do you create a file in Java if it does not exist?

mkdirs(); // Will create parent directories if not exists file. createNewFile(); FileOutputStream s = new FileOutputStream(file,false); All the above operations will throw an exception if the current user is not permitted to do the operation.

Which function is used to append text to a text file?

The WriteAllText method can be used to append to a text file by specifying that the append parameter is set to True .


1 Answers

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.

like image 88
Alan K Avatar answered Sep 22 '22 19:09

Alan K