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

2

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.

Sahib answered 15/8, 2015 at 21:55 Comment(0)
S
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.

Sahib answered 15/8, 2015 at 21:55 Comment(1)
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().Mallon
K
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();
    }
Kalasky answered 26/2, 2020 at 10:14 Comment(2)
dosn't work anymore 2023Quiteri
@Quiteri which version of Java you using ?Kalasky

© 2022 - 2024 — McMap. All rights reserved.