ayeama
ayeama

Reputation: 183

How to Save, Save As Java?

Hello I'm having a little bit of a problem with my text editor like program. I would like to have my Save feature work only if Save As has been called, and if Save is called that it appends the text From a JTextArea to the file created by Save As. I am using ActionListeners from JMenuItems to call the Save and Save As Actions. Here's the code for Save As:

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

Both the Save and Save As are nested inside static class ActionSaveAs implements ActionListener { public void actionPerformed(ActionEvent e) { ... } }

The problem is I can't access the String userProjectSavePath in the Save class so I can't append the new text to the same file as in the Save As.

Upvotes: 0

Views: 1815

Answers (1)

trashgod
trashgod

Reputation: 205785

Instead, let your notional saveDocument() method invoke saveDocumentAs() if currentFile is null. The following outline suggests the approach taken in Charles Bell's HTMLDocumentEditor, cited here.

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

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

Upvotes: 1

Related Questions