【问题标题】:How to save file.txt with JFileChooser?如何使用 JFileChooser 保存 file.txt?
【发布时间】:2014-10-08 23:16:25
【问题描述】:

我正在开发记事本项目,想知道如何保存文件.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();
        }

【问题讨论】:

    标签: java save jfilechooser notepad


    【解决方案1】:

    改变你的工作流程。

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

    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) {
            }
        }
    

    【讨论】:

      【解决方案2】:

      如果您希望另存为另存为,请让程序存储一个引用当前打开文件路径的文件对象,以便程序始终知道它正在编辑什么,然后只需写入程序文件变量

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-01
        • 1970-01-01
        • 2022-08-16
        • 2020-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多