Results 1 to 5 of 5
- 03-29-2011, 03:55 AM #1
Member
- Join Date
- Mar 2011
- Posts
- 10
- Rep Power
- 0
Problem writing multiple strings to a text file
Hi
I am writing a program where I will have to write many Strings into a text file, so I want to create a separate method to which I can pass a String and it will write the String to a new line in the file. But how many Strings I may pass it only writes the last one. Can someone please help me debug.
Here is the code:
Here I want to write 3 strings to a particular file , I dont want to copy code for all file readers and writers everytime I have to write.Java Code:import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Example { String logFile; BufferedWriter fileWrite; public static void main(String[] args) { Example ex = new Example(); ex.logFile = "log0.txt"; ex.log("1st line"); ex.log("2nd line"); ex.log("3rd line"); } public void log(String str) { try { fileWrite = new BufferedWriter(new FileWriter(logFile)); fileWrite.write(str); fileWrite.close(); } catch(IOException ex) { System.out.println("Error : cannot write into log file"); ex.printStackTrace(); } } }
Thanks and Regards
- 03-29-2011, 03:59 AM #2
Each time you try to write you create a new OutputStream to the file. Thus you will overwrite anything that is already in the file. Try creating the stream in "append" mode. Check the Java API.
- 03-29-2011, 04:11 AM #3
Member
- Join Date
- Mar 2011
- Posts
- 10
- Rep Power
- 0
Thank you, it works. I had not seen any example with append mode in any of the books.
Regards
- 03-29-2011, 09:59 PM #4
Member
- Join Date
- Mar 2011
- Posts
- 10
- Rep Power
- 0
Another query:
How can I modify the program so that log file is created by this name whenever the program runs and then strings are appended to it.
When I run program I dont want my results to be appended to old logfile. Any Help !
Regards
- 03-30-2011, 12:58 AM #5
Senior Member
- Join Date
- Mar 2011
- Posts
- 261
- Rep Power
- 3
Similar Threads
-
Writing multiple lines to text file at once
By Plex in forum New To JavaReplies: 14Last Post: 11-08-2010, 09:17 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 -
writing to text file problem
By blumdiggity in forum NetworkingReplies: 1Last Post: 02-26-2010, 02:43 PM -
text box listeners and returning multiple strings from methods
By int80 in forum New To JavaReplies: 5Last Post: 07-18-2008, 04:30 PM -
writing text to file
By notwist in forum New To JavaReplies: 3Last Post: 04-25-2008, 04:20 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks