• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting my program to write to an output file?  RSS feed

 
David Evangelista
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My program successfully reads a file, reports back what it finds and creates an output file. However, I cannot get it to write to the output file, it is always blank! Help me, Big Moose Saloon, you're my only hope.

Here's my code:

 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should close the file/reader/scanner after you finished using it.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

There are two reasons why you must close readers and writers, which includes that Scanner. One is that the file handle may never be properly closed, and that file may remain “in use” and unavailable to other code for ever. If you are using Java7/8, read about try‑with‑resources here; otherwise use a finally block.
The other reason (writers only) is that the Stream used may not be “flushed”, and all the data remain in the stream for ever and never get to the file. That is what PP was alluding to. There is no need to call flush() if you close the writer, because that usually flushes the Stream first.
Use System.err rather than System.out for error messages. Don't use System.exit, which won't do any harm in your simple application, but might in large multi‑threaded things.
Never, never, never close readers writer etc pointing to System.in, System.out, etc.

I added code tags to your post, which you should always use; doesn't it look better now

 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I meant close readers and writers pointing to files, etc. Not System.in, System.out. etc.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, something is not quite right with your else‑ifs. I suspect you have got a pair of {} which you don't need. Or maybe you have some redundant else statements. Please check the logic of that part of the code carefully.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!