• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Creating a new file using PrintWriter.

 
Kalona Ark
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a problem with the PrintWriter class. I am trying to get it to create an new file that has more than just the last line of the existing file. I want it to print all the lines from an existing file.


[ December 12, 2007: Message edited by: Kalona Ark ]
 
abhishek pendkay
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kalona,
your problem is not clear... whatever lines of code you have listed above seems to be fine... so if you can mention what exactly is the problem you are having or atleast provide your source code....
 
Rob Spoor
Sheriff
Pie
Posts: 20546
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to add to the file instead of overwriting its contents, you need to use FileWriter directly, as that has the possibility to specify whether to overwrite or append:


Don't be worried about using a FileWriter - this is exactly what PrintWriter uses when created using a String or File.
 
Kalona Ark
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I have 5 lines of text saved in "input.txt". I want it to have all 5 lines to show in the "output.txt".
[ December 12, 2007: Message edited by: Kalona Ark ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just open the file once, before the loop; and close it just once, after the loop. In other words, move the following three lines above the "while" loop:

File file = new File("output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);

And move this one outside the closing brace of the while loop:

output.close();

Just leave the output.println() call inside the loop.
 
Kalona Ark
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you soooo much. I was getting a major headache trying to figure this one out. I would have never thought of that.

Thanks to everyone else who have helped too.
[ December 12, 2007: Message edited by: Kalona Ark ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic