[英]How to save file.txt with JFileChooser?
I am developing notepad project, would like know how do for save a file.txt, my problem is, I keep the file opening JFileChooser, after selected the local where save intend, but after if save again will open JFileChoose again. 我正在开发记事本项目,想知道如何保存file.txt,我的问题是,我保持文件打开JFileChooser,选择了要保存的本地后,但是如果再次保存后将再次打开JFileChoose。 I want save.
我要保存。 Not save as.
不另存为。
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
PrintStream fileOut = null;
try {
File file = fc.getSelectedFile();
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (FileNotFoundException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
fileOut.close();
}
如果您想要另存为另存为,请让程序存储一个File对象,该对象引用当前打开的文件的路径,以便该程序始终知道其正在编辑的内容,然后只需将其写入文件中即可
Change you work flow. 改变您的工作流程。
Basically, when you first save the file, you need to keep a reference to the File
to which you saved to... 基本上,第一次保存文件时,需要保留对保存到的
File
的引用。
public class ... {
private File currentFile;
Now, when you go to save the file, you need to check if the currentFile
is null
or not. 现在,当您保存文件时,需要检查
currentFile
是否为null
。 It it is null
, you ask the user to select a file, otherwise, you can go ahead and try and save the file... 它为
null
,您要求用户选择一个文件,否则,您可以继续尝试并保存文件...
if (currentFile == null) {
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
}
}
// Used to make sure that the user didn't cancel the JFileChooser
if (currentFile != null) {
PrintStream fileOut = null;
try {
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (IOException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileOut.close();
} catch (IOException exp) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.