views:

51

answers:

3

Hello:

I am working on a program that loads and saves data from text files, and I am asking the user a file name with JFileChooser on load and save.

This question is about the save dialog: new JFileChooser().showSaveDialog();. The user then could overwrite an existing file without any warning, and that would be a problem.

Any suggestion on how to fix this? I have been looking for some method or option, but I didn't found anything.

Thanks in advance.

+1  A: 

Check before saving if the same file already exist then ask user for confirmation does she really want to override :p

 JDialog.setDefaultLookAndFeelDecorated(true);
    int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to override existing file?", "Confirm",
        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (response == JOptionPane.NO_OPTION) {
      System.out.println("No button clicked");
    } else if (response == JOptionPane.YES_OPTION) {
      System.out.println("Yes button clicked");
    } else if (response == JOptionPane.CLOSED_OPTION) {
      System.out.println("JOptionPane closed");
    }  

here is code

To check file already exist use

boolean exists = (new File("filename")).exists();
if (exists) {
    // File or directory exists
} else {
    // File or directory does not exist
}
org.life.java
+1  A: 

Maybe you could verify that the file does not already exists, and even give the JFileChooser a FileSystemView (see this constructor)

Riduidel
+1  A: 

Thanks for the answers, but I found another workaround, overriding the approveSelection() of the JFileChooser, this way:

JFileChooser example = new JFileChooser(){
@Override
public void approveSelection(){
    File f = getSelectedFile();
    if(f.exists && getDialogType() == SAVE_DIALOG){
        int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?","Existing file",JOptionPane.YES_NO_CANCEL_OPTION);
        switch(result){
            case JOptionPane.YES_OPTION:
                super.approveSelection();
                return;
            case JOptionPane.NO_OPTON:
                return;
            case JOptionPane.CANCEL_OPTION;
                cancelSelection;
                return;
        }
    }
    super.approveSelection();
}

I hope this could be useful for someone else.

rlbisbe