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

    Default 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

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

    Default

    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
  •