【发布时间】:2010-12-06 03:45:27
【问题描述】:
这是一段行为异常的代码。
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;
}
此代码导致的问题是,当我将已更改的文件保存回自身时,当文件大小小于打开时的大小时,保存的文本与显示的文本不同。我将向您展示所有 3 个文本示例。
打开的文件文本。
现在是所有好人都来援助他们的国家的时候了。
现在是所有好人来援助他们国家的时候了。
现在是所有好人来援助他们国家的时候了。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕狐跳过了懒狗的背。
改为。
现在是所有好人都来援助他们的国家的时候了。
现在是所有好人来援助他们国家的时候了。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕狐跳过了懒狗的背。
保存文件中的文本。在另一个编辑器中打开。
现在是所有好人都来援助他们的国家的时候了。
现在是所有好人来援助他们国家的时候了。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕狐跳过了懒狗的背。
懒狗回来了。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕狐跳过了懒狗的背。
如果将文本保存到新文件中,文本会很好地保存。
【问题讨论】:
标签: java