我有一个现有的文本文件并在其中编辑了一些内容。我想将一行文本保存到同一个文件中。目前,我的“保存”按钮将为我刚刚编辑的文本文件创建一个新文件。我想要的是我的“保存”按钮将覆盖现有文件。我需要在上面写什么代码?
这是我当前的代码:
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
int choice = fc.showSaveDialog(null);
if (choice == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getAbsolutePath();
writeToFile(filename);
}
}
这是我的 writeToFile 代码:
private void writeToFile(String filename) {
Person p = getPersonFromDisplay();
PersonFileMgr.save(filename, p);
}
最佳答案
覆盖文件而不创建整个新文件。使用 FileWriter
和 BufferedWriter
示例:
在您的writeToFile
方法中
try{
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hi\n");
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
关于java - 如何用 Java 编写保存按钮的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113453/