简体   繁体   中英

Writing to a File in Java

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM