Hi,
Here is a snippet of code that is behaving strange.
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;
}
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.
Opened file text.
Now is the time for all good men to come to the aid of their counrty.
Now is the time for all good men to come to the aid of their counrty.
Now is the time for all good men to come to the aid of their counrty.
The quick brown fox jumped over the lazy dogs back.
The quick brown fox jumped over the lazy dogs back.
The quick brown fox jumped over the lazy dogs back.
Changed to.
Now is the time for all good men to come to the aid of their counrty.
Now is the time for all good men to come to the aid of their counrty.
The quick brown fox jumped over the lazy dogs back.
The quick brown fox jumped over the lazy dogs back.
Text in saved file. Opened in another editor.
Now is the time for all good men to come to the aid of their counrty.
Now is the time for all good men to come to the aid of their counrty.
The quick brown fox jumped over the lazy dogs back.
The quick brown fox jumped over the lazy dogs back.
lazy dogs back.
The quick brown fox jumped over the lazy dogs back.
The quick brown fox jumped over the lazy dogs back.
The text saves fine if it is saved to a new file. Thanks for your help.