0

I am writing a little app and would like to add the same handler for two buttons: Save and Save As. For save if the file exists it should not open the JFileChooser,just save the content, but with my current code it always opens the dialog. How do I do this? Here's my code

public void actionPerformed(ActionEvent e) { JComponent source = (JComponent)e.getSource(); if (pathToFile.length()>0){ File file = new File(pathToFile); if (file.exists()){ try(FileWriter fw = new FileWriter(file.getName() + ".txt", true)){ fw.write(area.getText()); } catch(Exception ex){ System.out.println(ex.toString()); } } } else{ if (fchoser.showSaveDialog(source.getParent())== JFileChooser.APPROVE_OPTION){ try(FileWriter fw = new FileWriter(fchoser.getSelectedFile()+".txt")){ fw.write(area.getText()); f.setTitle(fchoser.getSelectedFile().getPath()); pathToFile = fchoser.getSelectedFile().getPath(); } catch(Exception ex){ } } } 

UPDATE Added code to check if file exsists. It does and there is no exception but the additional text does not write.

2
  • How do you do it ? By not calling showSaveDialog of course. Look into the File#exists method Commented Jun 4, 2016 at 14:57
  • Thanks, I updated my code but it still does not work. Commented Jun 4, 2016 at 19:25

1 Answer 1

1

Not related to your question but:

fw.write(area.getText()); 

Don't use the write method of a FileWriter. This will always write the text to the file using a "\n" as the line separator which may or may not be correct for the OS your code is running on.

Instead you can use the write(...) method of the JTextArea:

area.write(fw); 

Then the proper line separator will be used.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.