0

I have one of the biggest problem in my program. I've created Save button, but it saves if the .txt file is new (Then that button does "SaveAs" function). But when I open file, then type something and trying to save and it's not saving :S. Can anyone help me?

Here's the code:

fileSave.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if(currentFile == null) {
            int saveResult = fileSelect.showSaveDialog(null);
            if(saveResult == fileSelect.APPROVE_OPTION) {
                saveFile(fileSelect.getSelectedFile(), field.getText());            
            } else {
                saveFile(currentFile, field.getText());
            }
        }
    }
});

public void saveFile(File file, String contents) {
    BufferedWriter writer = null;
    String filePath = file.getPath();
    if(!filePath.endsWith(".txt")) {
        filePath += ".txt";
    }

    try {
        writer = new BufferedWriter(new FileWriter(filePath));
        writer.write(contents);
        writer.close();
        field.setText(contents);
        setTitle("Editex - " + filePath);
        currentFile = file;
    } catch (Exception e) {

    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 2
    Are you possibly swallowing the exception? Never do that, handle it. – Sotirios Delimanolis Nov 30 '13 at 07:41
  • Are you sure that `saveFile` executes when you try to save an existing opened file? I assume, that this if statement `if(currentFile == null)` does not let your method to be called. – polis Nov 30 '13 at 07:43
  • What is `field`? For better help sooner, post an [SSCCE](http://sscce.org/). In this case, if the field is a `JTextComponent`, it will have a method specifically for saving the content. Also, change code of the form `catch (Exception e) { ..` to `catch (Exception e) { e.printStackTrace(); // very informative! ..` – Andrew Thompson Nov 30 '13 at 07:54

1 Answers1

2

You aren't handling when currentFile != null, which is what I am assuming is the case when you are trying to save a file that already has a Filename.

Do something like this:

if(currentFile == null) {
    // Handle if new file
} else {
    // Handle an existing file
}

Move

saveFile(currentFile, field.getText());

into the else part of the above if else.

At the moment you have it within the if(currentFile == null), and this isn't the correct place as you are calling saveFile(null, field.getText()) here.


Also

catch(Exception e) {

}

is bad, never swallow an exception and do nothing with it, you will never know if an exception happens or not, just nothing will happen.

Tom Heard
  • 1,278
  • 10
  • 20