Results 1 to 4 of 4
Thread: Writing to a file
- 11-17-2010, 06:07 PM #1
Member
- Join Date
- Mar 2009
- Posts
- 45
- Rep Power
- 0
Writing to a file
Hi i'm doing an assignment where I got to write data to a text file. I can do this but I'm doing the method which calls this in a while loop and when a String is written to a file needs to be saved, each time the data is written to file it keeps overwriting the line before, my codes below:
This is in a method call but whenever I call the method again the old data is overwritten. Is there a way to change this so it saves the text on a new line?Java Code:String data = "this is the data I want to write on this method call"; String filename = "save.sav"; try { FileWriter writer = new FileWriter(filename); writer.write(data); writer.close(); } catch (IOException e){}
Thanks.
- 11-17-2010, 06:13 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
- 11-17-2010, 06:56 PM #3
Member
- Join Date
- Sep 2010
- Posts
- 21
- Rep Power
- 0
The error I see in your code is that you're declaring the new output file in the loop. So every time the loop iterates, it will create a new file with the same name and will therefore replace the previous one. In order for it to work you have to declare your output file outside of the loop and then just print to the output file within the loop. So for example:
So this declares the file outside of the loop, executes the loop and writes the data to the output file, exits the loop and then closes the output file.Java Code:String data = "this is the data I want to write on this method call"; String filename = "save.sav"; [COLOR="Red"]FileWriter writer = new FileWriter(filename);[/COLOR] try { writer.write(data); } [COLOR="Red"]writer.close();[/COLOR] catch (IOException e){}- Winners compare their achievements with their goals, while losers compare their achievements with those of other people. -
- 11-27-2010, 03:16 PM #4
Member
- Join Date
- Mar 2009
- Posts
- 45
- Rep Power
- 0
Similar Threads
-
reading a file and writing to a file....help!!!!
By java_prgr in forum New To JavaReplies: 3Last Post: 07-26-2010, 06:53 PM -
Im writing to a file and i want to skip lines while writing to a text file.
By Broden_McDonald in forum New To JavaReplies: 1Last Post: 02-27-2010, 01:29 AM -
Reading and Writing the contents of a file to another file
By priyankatxs in forum New To JavaReplies: 9Last Post: 10-20-2009, 10:52 AM -
[SOLVED] how to reading binary file and writing txt file
By tOpach in forum New To JavaReplies: 3Last Post: 05-09-2009, 11:31 PM -
swapping the contents of the file and writing to another file
By Ms.Ranjan in forum New To JavaReplies: 9Last Post: 07-10-2008, 04:52 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks