I'm sure there is a fairly simple answer to this question, so here we go.

I'm trying to use a FileWriter to write text to a file. My program reads text in from an already existing file, specified by the user and then asks whether to print the text to the console or to a new file, also to be named by the user.

I believe my problem is with passing the FileWriter to the "FileOrConsole" method. Am I not passing or declaring the FileWriter in the "FileOrConsole" method correctly? The file is always created but nothing is written to it.

2 Answers
2

you make classic error forgetting that parameters passed by value in case of java it is a value of the reference. The thing is that your assignment

out = new BufferedWriter(new FileWriter(response));

actually does not change the variable declared in main() it stays null

BufferedWriter out = null;
and then in finally it skips the close() by the if(out==null)
and as it is Buffered and you do no flush nothing is written to file.
what you got to do is out.close(); in side the FileOrConsole method call

OR

do the out = new BufferedWriter(new FileWriter(response));
outside of it. You choose :-)

Thank you Boris! I've updated the code in my question to show what I changed to get it working as I wanted. Could you try to explain again why exactly nothing is written if the BufferedWriter is not closed inside the method?
–
MarkJul 20 '11 at 23:46

Here's a code example of recommended practice for handling streams. Same approach can be used for input streams too and things like database code where it's important to always clean up after yourself to get the expected results.

Boris has it right. I think I'll head to bed. :)
–
brindyJul 20 '11 at 23:32

this is wrong answer. First: There is nothing to flush the out is null. Second: Close does flush() by itself. After I seen the comment - we all do our little mistakes :-)
–
Boris DaichJul 20 '11 at 23:33