title: Repeatedly Writing to a File
body: <p>I'm a moderately-experienced C++ guy slowly learning Java.  I'm writing a program which needs to do the following:</p>
  
  <ul>
  <li>Create a simple text file, default directory is fine</li>
  <li>As the program runs, periodically write one line of data to the file.  Depending on a number of factors, the program may write to the file once or a million times.  There is no way of knowing which write will be the last.</li>
  </ul>
  
  <p>I've been researching different ways to do this, and this is the working code I've come up with.  There are two files, "PeteProgram.java" and "PeteFileMgr.java" :</p>
  
  <pre><code>/*
  "PeteProgram.java"
  */
  
  import java.io.*;
  import java.lang.String;
  
  public class PeteProgram {
  
      public static void main(String[] args) throws IOException {
  
        String PeteFilename="MyRecordsFile.txt";
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PeteFilename), "utf-8"));
        PeteFileMgr MyPeteFileMgr = new PeteFileMgr(writer);
  
        MyPeteFileMgr.AddThisString(writer, "Add this line #1\n");
        MyPeteFileMgr.AddThisString(writer, "Add this line #2\n");
        MyPeteFileMgr.AddThisString(writer, "Add this line #3\n");
  
      }
  }
  
  
  //=====================================================================================================
  //=====================================================================================================
  
  
  /*
  "PeteFileMgr.java"
  */
  
  import java.io.*;
  
  public class PeteFileMgr {
  
    public PeteFileMgr(Writer writer) {
  
         try {
            writer.write("File created!");
  
               } catch (IOException ex) {
            // report
            } finally {
               try {writer.close();} catch (Exception ex) {}
            }
        }
  
    void AddThisString(Writer writer, String AddThis) {
  
      try {
            writer.append(AddThis);
  
               } catch (IOException ex) {
            // report
            } finally {
               try {writer.close();} catch (Exception ex) {}
            }
        } 
    }   
  </code></pre>
  
  <p>The initial creation of the file works just fine.  However, the to-be-added lines are not written into the file.  Because the program compiles and runs with no errors, I assume the program tries to write the added lines, fails, and throws an exception.  (Unfortunately, I am working with a primitive compiler/debugger and can't see if this is the case.)</p>
  
  <p>Does anyone spot my mistake?</p>
  
  <pre><code>       Many thanks!
              -P
  </code></pre>