【问题标题】:How to Save, Save As Java?如何保存,另存为Java?
【发布时间】:2023-04-07 08:41:01
【问题描述】:

您好,我的文本编辑器(例如程序)有点问题。我想让我的保存功能只有在调用另存为的情况下才能工作,并且如果调用保存它会将文本从 JTextArea 附加到另存为创建的文件中。我正在使用 JMenuItems 中的 ActionListeners 来调用保存和另存为操作。这是另存为的代码:

FileDialog fileDialogSave = new FileDialog(frame, "Save", FileDialog.SAVE);
fileDialogSave.setVisible(true);        
String userProjectSavePath = fileDialogSave.getDirectory() + fileDialogSave.getFile();
File userProjectSave = new File(userProjectSavePath);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(userProjectSave, true)))) {
userProjectSave.createNewFile();
String userProjectNameToSave = codeArea.getText();
out.println(userProjectNameToSave);
} catch (IOException e1) {
    e1.printStackTrace();
}

保存和另存为都嵌套在static class ActionSaveAs implements ActionListener { public void actionPerformed(ActionEvent e) { ... } }

问题是我无法访问 Save 类中的 String userProjectSavePath,因此我无法将新文本附加到与 Save As 相同的文件中。

【问题讨论】:

  • 为了尽快获得更好的帮助,请发布MCTaRE(经过测试和可读的最小完整示例)。

标签: java swing save actionlistener


【解决方案1】:

如果currentFilenull,则让您的名义saveDocument() 方法调用saveDocumentAs()。以下大纲建议了 Charles Bell 的 HTMLDocumentEditor 中采用的方法,引用了 here

public void saveDocument() {
    if (currentFile != null) {
        // Save in currentFile
    } else {
        saveDocumentAs();
    }
}

public void saveDocumentAs() {
    // Check before overwriting existing file
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多