Java I/O problem the string was written but didn’t show on the file

I create an I/O class to read and append some text to a file.

I supposed it has been written but for some reasons it’s not shown in the file – although the program recognize it.

The file TestResult.csv is in the src/main/resources folder inside the program folder.

I learned how to open and read it from an tutorial on HowToDoInJava: Read a file from the ‘resources’ folder.

My Code

The first couple of code lines are pretty similar to the example in the website.

import java.io.*;
import java.nio.file.Files;
import java.io.FileWriter;

public class ReadResourceFileDemo {

    public static void main(String[] args) throws IOException {
        //open file
        ClassLoader classLoader = IOLab.class.getClassLoader();
        File file = new File(classLoader.getResource("TestResult.csv").getFile());

        //append
        try (FileWriter fw=new FileWriter(file, true)) {
            fw.append("nJulie,Brown,100,A");
            String content = new String(Files.readAllBytes(file.toPath()));
            System.out.println(content);
        }
    }
}

What I got in TestResult.csv

Alex,Smith,99,A
Jolene,Schmidt,100,A
Mackinzie,Jensen,86,B

The goal is to append the String to the TestResult.csv.

After I ran the first time the result was:

Alex,Smith,99,A
Jolene,Schmidt,100,A
Mackinzie,Jensen,86,B

Then I run again for the second time and got:

"C:Program FilesJavajdk-16.0.2binjava.exe" "-javaagent:C:Program 
FilesJetBrainsIntelliJ IDEA 2021.2.1libidea_rt.jar=56365:C:Program 
FilesJetBrainsIntelliJ IDEA 2021.2.1bin" -Dfile.encoding=UTF-8 -classpath 
C:UserstuantIdeaProjectsuntitledtargetclasses edu.sdccd.cisc191.ReadResourceFileDemo
Alex,Smith,99,A
Jolene,Schmidt,100,A
Mackinzie,Jensen,86,B
Julie,Brown,100,A

Process finished with exit code 0

Issue

This means for the first time the program skipped the append or it did but didn’t show in the file for some reason.

When I open the file TestResult.csv it only has the first 3 lines.

However, the 4th line that appended manually as Julie,Brown,100,A didn’t show up.

Thanks a lot for any help!

Answer

What happened

When you open and write the first time, it is written to a buffer. This buffer is maintained inside the try-with block. But the buffer is not yet flushed. It is flushed either by explicitly calling flush() or by closing the IO-stream/writer which is done implicitly by close():

Closes the stream, flushing it first.

And close is automatically and implicitly called when the try block ends with the closing curly-brace }. This resource-saving attitude of try-with block is the benefit of a concept called auto-closable. The interface AutoCloseable is implemented by most IO-steams like FileWriter.

As your independent read-operation Files.readAllBytes(file.toPath()) is also inside this try-with block, it reads from the file at disk, not from the buffer.

How to fix

Theoretically it would be logical to read from the buffer of fw, but this is not easily possible.

However you can either flush the buffer inside the try-with block using fw.flush() and then read. This flush writes the buffer to disk, so you can read from the disk and expect the flushed content appearing read.

Or you can move the read-operation after the try-with block which assures that buffer was flushed and written before.

Both fixes are suggested in Epicblood’s answer – somewhat obsolete but effective.