如何用Java编写Save按钮的函数?
我有一个现有的文本文件,并在其中编辑了一些内容。我想在同一个文件中保存一行文本。目前,我的保存按钮将为我刚刚编辑的文本文件创建一个新文件。我想要的是,我的“保存”按钮只会覆盖现有文件。我需要在上面写什么代码 以下是我当前的代码:如何用Java编写Save按钮的函数?,java,file,button,text,save,Java,File,Button,Text,Save,我有一个现有的文本文件,并在其中编辑了一些内容。我想在同一个文件中保存一行文本。目前,我的保存按钮将为我刚刚编辑的文本文件创建一个新文件。我想要的是,我的“保存”按钮只会覆盖现有文件。我需要在上面写什么代码 以下是我当前的代码: private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser fc = new
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());
}
}
你可以这样做:
InputStream ios = null;
OutputStream out = null;
try {
ios = new FileInputStream(file);
byte[] buffer = new byte[SIZE];
int read;
out = new FileOutputStream(file);
while ((read = ios.read(buffer)) != -1) {
out.write(buffer, 0, read);
out.flush();
}
} catch (IOException e) {
log.error("Saving failed", e);
} finally {
if (ios != null) {
ios.close();
}
if (out != null) {
out.close();
}
}
请注意,在我们当前的代码中,您不需要几个变量作为选项和文件名,您可以将它们内联。没有理由拥有它们。您现在有什么代码?writeToFile方法在哪里?抱歉,花了太长时间。