cAMPy
cAMPy

Reputation: 587

Java swing Save and Save as functions with JFileChooser

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.

Upvotes: 0

Views: 380

Answers (1)

camickr
camickr

Reputation: 324207

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.

Upvotes: 1

Related Questions