Java 如何使用JFileChooser保存file.txt?

Java 如何使用JFileChooser保存file.txt?,java,save,jfilechooser,notepad,Java,Save,Jfilechooser,Notepad,我正在开发记事本项目,想知道如何保存一个file.txt文件,我的问题是,我一直在打开JFileChooser文件,在选择了本地保存打算,但如果保存后再次将打开JFileChoose再次。我要存钱。不另存为 JFileChooser fc = new JFileChooser(); int resp = fc.showSaveDialog(fc); if (resp == JFileChooser.APPROVE_OPTION) { PrintStream

我正在开发记事本项目,想知道如何保存一个file.txt文件,我的问题是,我一直在打开JFileChooser文件,在选择了本地保存打算,但如果保存后再次将打开JFileChoose再次。我要存钱。不另存为

  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();
        }

如果希望另存为另存为,请让程序存储一个引用当前打开文件路径的文件对象,以便程序始终知道正在编辑的内容,然后只需写入程序文件变量即可更改工作流程

基本上,当您第一次保存文件时,您需要保留对您保存到的
文件的引用

public class ... {
   private File currentFile;
现在,当您要保存文件时,需要检查
currentFile
是否为
null
。如果它是
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) {
        }
    }