• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java IO question  RSS feed

 
Angel Kal
Greenhorn
Posts: 17
Chrome Netbeans IDE Windows Vista
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im studying for a test...and one of the sections were covering this time is file IO. The instructor gave us some powerpoints which go through stuff step by step...but when it comes to writing to a text file (without erasing previous entries, or appending), her method isnt working. The way I was thinking about it every time I ran this, it should add another "Im in your file" line to the text file. But every time I check it there's only one "Im in your file".

Can someone point out for me why this is not working/apppending the file each time it is ran?

 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


You're creating a new FileWriter, in append mode, which will add lines to the existing file. But then you're totally ignoring that FW and creating a PrintWriter that doesn't use that FW and instead just goes directly to the file, with no appending. Your second line needs to be


And then, since you're calling pw.close(), you won't need to call fw.flush(). PW's close() will flush and close any wrapped Writers or OutputStreams.
 
Angel Kal
Greenhorn
Posts: 17
Chrome Netbeans IDE Windows Vista
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean that the printwriter should come before the file writer, or the argument for the printwriter should be the filewriter I just created (fw)?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angel Kal wrote:Do you mean that the printwriter should come before the file writer, or the argument for the printwriter should be the filewriter I just created (fw)?


Oops, sorry. I copy/pasted and didn't change it.

The second one:


Of course, while you were waiting for me to respond, you could have just tried it.
 
Angel Kal
Greenhorn
Posts: 17
Chrome Netbeans IDE Windows Vista
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had a feeling thats what you meant, I bet it was a typo she didnt catch while she was presenting somehow....Thank you for your time and help
 
Paul Clapham
Sheriff
Posts: 22834
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, copy-paste-forget-to-edit is a very common error (see this thread for an example!) so it could be that your instructor made that error.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!