Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to append data to a file

 
Suresh Kanagalingam
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Can anyone tell me how I can open a file in append mode and write to the end of file? I tried 'PrintWriter' and each time when I run the program it is overwriting the original file!
Thanks
Suresh
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create the PrintWriter with a FileOutputStream, using the constructor for the Stream that takes a String for the filename, and a boolean for appending. Should look like this:
PrintWriter writer = new PrintWriter( new FileOutputStream( "filename.ext" , true ) );
 
Suresh Kanagalingam
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jason,
The method you identified does not work due to a bug in Java (according to Sun @ http://java.sun.com).
Work around is to have a class to identify the file existance and write or not write file header - and this works!
Thanks for your reply
Suresh
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, was not aware of that bug (my bad, didn't actually try out the code).

Thanks for the info!
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm, you know, I just tried it out, and it works! Here's all I did:

Using JDK 1.3.1. When I ran this the first time, my test.dat file had this:
This is the first test
This is another test
Ran it a second time, had this:
This is the first test
This is another test
This is the first test
This is another test
Ran it a third time:
This is the first test
This is another test
This is the first test
This is another test
This is the first test
This is another test
I think you get the point. You sure the bug was in reference to this?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!