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.
showSaveDialogof course. Look into theFile#existsmethod