Results 1 to 2 of 2
- 07-22-2011, 02:01 AM #1
Member
- Join Date
- Jul 2011
- Posts
- 5
- Rep Power
- 0
Trying to write to a file but it only prints last line
So,
I used the PrintWriter fout and it creates the new file secret.txt but it only writes the last line, why could this be, am I missing something?
Java Code:import java.io.*; public class NsaEncoder { public static void main(String[] argv) throws Exception { BufferedReader fin; BufferedReader cin; cin = new BufferedReader(new InputStreamReader(System.in)); // open a file whose name is entered by the user String fileName; System.out.println("What file do you want to use for input? "); fileName = cin.readLine(); fin = new BufferedReader(new FileReader(fileName)); while (true) { if (!fin.ready()) break; String lineFromFile; lineFromFile = fin.readLine(); String sNew = ""; for (int i = 0; i < lineFromFile.length(); i++) sNew += (char)(lineFromFile.charAt(i) + 1); System.out.println(sNew); PrintWriter fout; fout = new PrintWriter(new FileWriter("secret.txt")); fout.print(sNew); fout.close(); } // while fin.close(); } // main } // public class
- 07-22-2011, 02:19 AM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,068
- Blog Entries
- 3
- Rep Power
- 15
Your printwriter is initialized in the loop each time. This is going to write over the first line each time through the loop. It's also terribly slow if you solve the bug. The print writer should be initialized outside of loops and open the file only once, then write to the file until you are done with it. Finally, you close it.
Similar Threads
-
Java- Writing a file and reading a file line by line
By Nazneen Ali in forum New To JavaReplies: 7Last Post: 07-20-2011, 08:56 AM -
write to file one line at a time and keep all contents
By stringargs in forum New To JavaReplies: 1Last Post: 02-11-2011, 07:09 PM -
Write to a specific line in a file
By phantom06 in forum New To JavaReplies: 1Last Post: 02-05-2011, 07:32 PM -
write line multiple times
By relith in forum New To JavaReplies: 3Last Post: 10-27-2010, 09:38 AM -
Write to line in file
By blackstormattack in forum New To JavaReplies: 3Last Post: 03-09-2009, 01:59 PM
Bookmarks