Results 1 to 2 of 2
  1. #1
    beauti477 is offline Member
    Join Date
    Jul 2011
    Rep Power

    Default Trying to write to a file but it only prints last line

    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:
    public class NsaEncoder	 
      public static void main(String[] argv) throws Exception 
        BufferedReader fin;
        BufferedReader cin;
        cin = new BufferedReader(new InputStreamReader(;
        // 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); 
          PrintWriter fout;
          fout = new PrintWriter(new FileWriter("secret.txt"));
        } // while 
      // main 
    } // public class

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Richmond, Virginia
    Blog Entries
    Rep Power


    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

  1. Java- Writing a file and reading a file line by line
    By Nazneen Ali in forum New To Java
    Replies: 7
    Last Post: 07-20-2011, 08:56 AM
  2. write to file one line at a time and keep all contents
    By stringargs in forum New To Java
    Replies: 1
    Last Post: 02-11-2011, 07:09 PM
  3. Write to a specific line in a file
    By phantom06 in forum New To Java
    Replies: 1
    Last Post: 02-05-2011, 07:32 PM
  4. write line multiple times
    By relith in forum New To Java
    Replies: 3
    Last Post: 10-27-2010, 09:38 AM
  5. Write to line in file
    By blackstormattack in forum New To Java
    Replies: 3
    Last Post: 03-09-2009, 01:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts