Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a File in Java

Tags:

java

file-io

I'm really new to Java, and I can't write to a file for some reason, 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 fileLocation, I see my file, but it's empty. My log does say "test was supposed to be written to the file"

What could I be doing wrong here?

Thanks!

UPDATE: My FileLocation variable is a string:

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

I'm using a Mac

like image 959
Doug Molineux Avatar asked Jun 25 '26 12:06

Doug Molineux


1 Answers

Code is fine. Are you checking the right file location? Perhaps you had created the file you're checking before; while your program could be writing elsewhere.

like image 121
jbasko Avatar answered Jun 27 '26 03:06

jbasko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!