Strange behavior of RandomAccessFile object
<p>Here is a snippet of code that is behaving strange.</p>

<pre><code>    private void saveToFile() throws IOException {
 JFileChooser fileChooser = new JFileChooser();
 File name = null;

     int returnVal = fileChooser.showSaveDialog(fileChooser);

 //Sets the variable name to the file the user selected.
 if (returnVal == JFileChooser.APPROVE_OPTION) {
          name = fileChooser.getSelectedFile();
        //Exits the method if the user selected cancel in the dialog box.
 }else if (returnVal == JFileChooser.CANCEL_OPTION) {
          return;
        }

 //Writes the text data to a file.
 try {
  //Writes the text in the textArea to the file which was selected.
  RandomAccessFile raf = new RandomAccessFile(name, "rw");
  raf.writeBytes(textArea.getText());
  raf.close();
 //Display the stack trace and an error message if the file could not be written.
 } catch (IOException e) {
  e.printStackTrace();
  System.err.print("    Cannot process file....\n");
 }

        //Displays the filename of which the file was saved to.
 String fileName = name.getName();
        super.setTitle("XText: " + fileName);

    //The text has now been saved and is no longer considered changed.
    changed = false;
}
</code></pre>

<p>The problem this code causes is when I save a file that was changed, back to itself and when the size is smaller that when it was when it was opened, the text saved is not the same as the text shown. I will show you all 3 text examples.</p>

<p>Opened file text.</p>

<p>Now is the time for all good men to come to the aid of their counrty.<br />
  Now is the time for all good men to come to the aid of their counrty.<br />
  Now is the time for all good men to come to the aid of their counrty.<br />
  The quick brown fox jumped over the lazy dogs back.<br />
  The quick brown fox jumped over the lazy dogs back.<br />
  The quick brown fox jumped over the lazy dogs back.  </p>

<p>Changed to.</p>

<p>Now is the time for all good men to come to the aid of their counrty.<br />
  Now is the time for all good men to come to the aid of their counrty.<br />
  The quick brown fox jumped over the lazy dogs back.<br />
  The quick brown fox jumped over the lazy dogs back.  </p>

<p>Text in saved file. Opened in another editor.</p>

<p>Now is the time for all good men to come to the aid of their counrty.<br />
  Now is the time for all good men to come to the aid of their counrty.<br />
  The quick brown fox jumped over the lazy dogs back.<br />
  The quick brown fox jumped over the lazy dogs back.  </p>

<p>lazy dogs back.<br />
  The quick brown fox jumped over the lazy dogs back.<br />
  The quick brown fox jumped over the lazy dogs back.  </p>

<p>The text saves fine if it is saved to a new file. Thanks for your help.</p>
