File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Creating a new file using PrintWriter. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Creating a new file using PrintWriter." Watch "Creating a new file using PrintWriter." New topic
Author

Creating a new file using PrintWriter.

Kalona Ark
Greenhorn

Joined: Oct 31, 2007
Posts: 20
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

Joined: Jan 01, 2007
Posts: 184
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....


The significant problems we face cannot be solved by the same level of thinking which created them – Einstein
SCJP 1.5, SCWCD, SCBCD in the making
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19761
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Kalona Ark
Greenhorn

Joined: Oct 31, 2007
Posts: 20


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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Kalona Ark
Greenhorn

Joined: Oct 31, 2007
Posts: 20
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Creating a new file using PrintWriter.