title: Appending One File to Another in Java - Why Does My Code Overwrite?
body: <p>I'm a moderately-experienced C++ guy learning Java and having a great time learning on this website.  Recently, I did some research on how Java can append one file to another.  Suppose I have two files.  Here's C:\tmp\permFile.txt:</p>
  
  <pre><code>Line A:   abcef
  Line B:   ghijk
  Line C:   lmnop
  </code></pre>
  
  <p>And here's C:\tmp\tmpFile.txt:</p>
  
  <pre><code>line 1:   1234567890
  line 2:   0123456789
  line 3:   9012345678
  line 4:   8901234567
  </code></pre>
  
  <p>The objective here is simple; I want to append tmpFile.txt to the end of permFile.txt.  I researched code to do this and thought I had the problem solved.  Only today I noticed that permFile.txt looks like this after running the code:</p>
  
  <pre><code>Line A:   abcef
  Line B:   ghijk
  Line C:   lmnop:   9012345678
  line 4:   8901234567
  </code></pre>
  
  <p>I think what is happening here is permFile is 48 characters long (16 chars/line).  My code counts exactly 48 chars into tmpFile and appends from the 49th character on out.  Weird, huh?</p>
  
  <p>Here's the code:</p>
  
  <pre><code>import java.io.*;
  
  public class myProgram {
     public static void main(String[] args) throws IOException {
  
        // Define two filenames:
        String permFile = "C:\tmp\permFile.txt";
        String tmpFile =  "C:\tmp\tmpFile.txt";
  
        appendFiles appender = new appendFiles(permFile, tmpFile);
        }
  }
  
  public class appendFiles {
      public static void appendFiles(String permFile, String tmpFile) throws IOException {
      // Appends file "tmpFile" to the end of "permFile"
      // Code adapted from:  https://www.daniweb.com/software-development/java/threads/44508/appending-two-java-text-files
  
          try {
          // create a writer for permFile
          BufferedWriter out = new BufferedWriter(new FileWriter(permFile, true));
          // create a reader for tmpFile
          BufferedReader in = new BufferedReader(new FileReader(tmpFile));
          String str;
          while ((str = in.readLine()) != null) {
              out.write(str);
              }
          in.close();
          out.close();
          } catch (IOException e) {
          }
      }
  }
  </code></pre>
  
  <p>What I suspect I need to do is add a line which "points" the "out" BufferedWriter to the <em>END</em> of permFile, not the beginning.  But my attempts to do this have been disastrous and not worth detailing here.  Also, what I don't get is why the contents of tmpFile do not overwrite all of permFile if "out" is pointed at the start of permFile.  Suspect I'm making a simple, rookie mistake.</p>
  
  <p>Many thanks!  -P</p>
  
  <p>PS - Can't tell you how much I love this site.  I always try to research my own solutions, but when you get stuck on a specific problem, there's no substitute to asking real people for help.</p>