5 Replies Latest reply: Apr 20, 2007 1:51 PM by 800282 RSS

    Java write/append to each line of a text file

    807599
      I have spent numerous hours trying to figure out what I am doing wrong. If anyone more experienced could tell me what is wrong with my code.

      I have a very simple text file with 5 lines:

      line1
      line2
      line3
      line4
      line5

      All I am trying to do is append some string to the end of each of those lines. Everytime I run my code, it erases all content but does not write/append anything to the file. Any help is greatly appreciated.
      Thanks! I am about to throw this monitor out the window!!
      package Chapter6;
      
      import java.io.*;
      
      public class fileNavigation2 {
      
      
           public static void main(String[] args) {
           
                File dir = new File("C:\\testing");
                System.out.println(dir.isDirectory());
                
                
                try {
                     File file = new File(dir, "Test.txt");
                     FileReader fr = new FileReader(file);
                     BufferedReader br = new BufferedReader(fr);
                     FileWriter fw = new FileWriter(file);
                     BufferedWriter bw = new BufferedWriter(fw);
                     
                     String s = "Add1,";
                     String s2 = "Add2\n";
                     String str;
                     
                     while((str = br.readLine()) != null) {
                     StringBuffer sb = new StringBuffer(str);
                     sb.append(s + s2);
                     String y = sb.toString();
                     System.out.println(sb);
                     System.out.println("Appending");
                     bw.write(y);
                     }
                     
                     bw.close();
                     System.out.println("Done");
                     
                     
                }catch(IOException e) {}
                
      }
      }
        • 1. Re: Java write/append to each line of a text file
          800282
          Don't stuff all your logic into the main method, here's a better way:
          import java.io.*;
          import java.util.*;
          
          public class Main {
              
              static void appendTo(String fileName, String[] newLines) throws IOException {
                  List<String> allLines = getLinesFrom(fileName);
                  for(String line : newLines) {
                      allLines.add(line);
                  }
                  writeLinesTo(fileName, allLines);
              }
              
              static List<String> getLinesFrom(String fileName) throws IOException {
                  List<String> lines = new ArrayList<String>();
                  Scanner file = new Scanner(new File(fileName));
                  while(file.hasNextLine()) {
                      lines.add(file.nextLine());
                  }
                  file.close();
                  return lines;
              }
              
              static void writeLinesTo(String fileName, List<String> lines) throws IOException {
                  BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
                  for(String line : lines) {
                      out.write(line);
                      out.write(System.getProperty("line.separator"));
                  }
                  out.close();
              }
              
              public static void main(String[] args) {
                  String fileName = "Test.txt";
                  String[] extraLines = {
                          "a new line",
                          "and yet another new line"
                          };
                  try {
                      appendTo(fileName, extraLines);
                      System.out.println("Done.");
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
          Good luck.
          • 2. Re: Java write/append to each line of a text file
            807599
            First, thanks a lot for your feedback. The code makes a lot of sense but it does not update the content of my Test.txt file.

            I only edited the line of code that creates the new file so that it could find the location of the file.
            Scanner file = new Scanner(new File("C:\\testing",fileName));
            ==============================
            The code now looks like:
            import java.io.*;
            import java.util.*;
             
            public class Main {
                 
                
                static void appendTo(String fileName, String[] newLines) throws IOException {
                    List<String> allLines = getLinesFrom(fileName);
                    for(String line : newLines) {
                        allLines.add(line);
                    }
                    writeLinesTo(fileName, allLines);
                }
                
                static List<String> getLinesFrom(String fileName) throws IOException {
                    List<String> lines = new ArrayList<String>();
                    Scanner file = new Scanner(new File("C:\\testing",fileName));
                    while(file.hasNextLine()) {
                        lines.add(file.nextLine());
                    }
                    file.close();
                    System.out.println(lines);
                    return lines;
                }
                
                static void writeLinesTo(String fileName, List<String> lines) throws IOException {
                    BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
                    for(String line : lines) {
                        out.write(line);
                        out.write(System.getProperty("line.separator"));
                    }
                    out.close();
                }
                
                public static void main(String[] args) {
                    String fileName = "Test.txt";
                    String[] extraLines = {
                            "a new line",
                            "and yet another new line"
                            };
                    try {
                        appendTo(fileName, extraLines);
                        System.out.println("Done.");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            Again, thanks for the help.
            • 3. Re: Java write/append to each line of a text file
              800282
              First, thanks a lot for your feedback. The code
              makes a lot of sense but it does not update the
              content of my Test.txt file.

              I only edited the line of code that creates the new
              file so that it could find the location of the file.

              Scanner file = new Scanner(new File("C:\\testing",fileName));

              That's because your FileWriter does not write to the "C:\\testing" directory.
              But browsing through the FileWriter class, I saw a much easier way to do this:
              import java.io.*;
               
              public class Main {   
              
                  static void appendLinesTo(String fileName, String[] lines) throws IOException {
                      BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
                      for(String line : lines) {
                          out.write(line);
                          out.write(System.getProperty("line.separator"));
                      }
                      out.close();
                  }
                  
                  public static void main(String[] args) {
                      String fileName = "C:/testing/Test.txt";
                      String[] extraLines = {
                              "a new line",
                              "and yet another new line"
                              };
                      try {
                          appendLinesTo(fileName, extraLines);
                          System.out.println("Done.");
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
              Good luck.
              • 4. Re: Java write/append to each line of a text file
                807599
                Thanks for the additional help. I got it to work and I spent some time trying to make it so that instead of appending to the end of the file, each line is appended the desired string.

                For example, a file with lines:

                line1
                line2
                line3

                would then become:

                line1, appended string
                line2, appended string
                line3, appended string

                Thanks again for the great help.
                • 5. Re: Java write/append to each line of a text file
                  800282
                  Thanks for the additional help. I got it to work and
                  I spent some time trying to make it so that instead
                  of appending to the end of the file, each line is
                  appended the desired string.

                  For example, a file with lines:

                  line1
                  line2
                  line3

                  would then become:

                  line1, appended string
                  line2, appended string
                  line3, appended string
                  Then you'll need to go back to my code snippet from reply #1 and change the method
                  static void appendTo(String fileName, String[] newLines) throws IOException
                  in such a way that it doesn't add the contents of newLines at the end of the List<String> but replaces the String's from the List<String> with the contents from the List<String> itself with an appended String added to it.
                  Have a look at the set(...) method for this:
                  http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html#set&%40;int, E&#41;

                  Thanks again for the great help.
                  You're welcome.