3

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

7
  • What if you try to also do fstream.flush(); fstream.close(); ? Commented Mar 8, 2011 at 23:03
  • 1
    You forgot to close the filewriter Commented Mar 8, 2011 at 23:04
  • 2
    The code works for me. The underlying writer should be closed as well, when the BufferedWriter is closed, shouldn't it? Maybe there is a problem concerning access rights? Have you tried a folder where you have full access? Commented Mar 8, 2011 at 23:06
  • 2
    @starcorn, that doesn't matter. Closing the outermost wrapper is sufficient, even though I'd have done it in finally. The flush() call is also unnecessary since close already implicitly does that. Commented Mar 8, 2011 at 23:09
  • 1
    The accepted answer indicates that this is a problem that can not be reproduced (by someone running the test correctly) Commented Dec 11, 2014 at 7:52

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are correct, I am using Vaadin to make this file downloadable, so each time I downloaded it, it was empty, but the original file appears to have "test" in it. Thanks for the suggestion :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.