• Post Reply Bookmark Topic Watch Topic
  • New Topic

Writing to a text file with BufferedWriter ?  RSS feed

 
AhFai Chan
Ranch Hand
Posts: 81
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am reading from one text files and writing the output to a new text file.

My code went and created the output text file, but does not populate it, i.e. it is an empty file.

It does print the inbound text files to the screen nicely, with line number.

What have I done wrong this time?


 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know. That is quite old‑fashioned code; you should use the new Date classes rather than java.util.Date.
One thing: you should close the “outside” objects. Your outermost reader is the line number reader, so you close that, and you don't need to close the other two readers. Your outermost writer is the buffered writer but you haven't closed that. If you don't close the buffered writer you may never flush it and you get nothing in the output file. Not sure whether that is the cause of your problem, but it is worth considering.

Suggest: Close only the lnr and the bw. Find out how to open the writers with try‑with‑resources and you can forget about closing because it is all done automatically.
 
AhFai Chan
Ranch Hand
Posts: 81
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Don't know. That is quite old‑fashioned code; you should use the new Date classes rather than java.util.Date.
One thing: you should close the “outside” objects. Your outermost reader is the line number reader, so you close that, and you don't need to close the other two readers. Your outermost writer is the buffered writer but you haven't closed that. If you don't close the buffered writer you may never flush it and you get nothing in the output file. Not sure whether that is the cause of your problem, but it is worth considering.

Suggest: Close only the lnr and the bw. Find out how to open the writers with try‑with‑resources and you can forget about closing because it is all done automatically.


Thanks, it works. Amazing how the order of closing the readers make such a big difference.

About old fashioned codes, the last time I Java-ed was 10 years ago, it has been a learning experience coming back up to speed. Sorry about that.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done

Learn the new date classes from the Java™ Tutorials and see how much better they are than the old classes.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!