Writing to a file in Java

I am really new to Java, and for some reason I cannot write to a file, my code looks like this:

FileWriter fstream;
    try {
        fstream = new FileWriter(fileLocation);
        BufferedWriter out = new BufferedWriter(fstream);
        log.info("test was supposed to be written to the file");
        out.write("test");

        out.flush();
        out.close();

    } catch (IOException e) {
        log.error("File not created ", e);
    }

When I go to the file, I see my file, but it is empty. My journal says that "the test should have been written to a file"

What can i do wrong?

Thank!

UPDATE: My FileLocation variable is a string:

private String fileLocation="/Users/s/out.txt";

I am using a mac

+3
source share
1 answer

The code is ok. Are you checking the location of the file? You may have created a file that you are checking earlier; while your program may write elsewhere.

+3
source

All Articles