19

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.

2 Answers 2

33

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.

1
  • 5
    Useful post. It's important to use both CREATE and APPEND options, as you've done. With APPEND only, you get an exception if the file doesn't exist, but this is not explicitly mentioned in the API documentation. By the way, you would find it much easier to use a PrintWriter than a BufferedWriter. Or even just use Files.write(). Commented Dec 16, 2015 at 11:19
5

You can also try this :

    Path path = Paths.get("C:\\Users", "textfile.txt");
    String text = "\nHello how are you ?";


    try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND,StandardOpenOption.CREATE)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
2
  • dosn't work anymore 2023 Commented Oct 2, 2023 at 7:46
  • @user1034912 which version of Java you using ? Commented Oct 4, 2023 at 2:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.