3

After a bit of googling I'm not seeing this turn up much. Is there some "generic" way to forces the user to select a file that "already exists"

I could add something like http://coding.derkeiler.com/Archive/Java/comp.lang.java.help/2004-01/0302.html or like JFileChooser with confirmation dialog but is there some canonical way?

Thanks.

Community
  • 1
  • 1
rogerdpack
  • 62,887
  • 36
  • 269
  • 388

3 Answers3

3

First you need to check if your better option is choser.showOpenDialog or showSaveDialog

Save Dialog will let you select any name in the specified path it could be a non existent file, but open will always accept the selected file.. and you can safely add a file.exists() to ensure the file exists. You can also change the text of the buttons.. dialog.. etc..

JFileChooser chooser = new JFileChooser();
    chooser.setApproveButtonText("Save");
    int result = chooser.showOpenDialog(null);
    if(result == JFileChooser.APPROVE_OPTION){
        File selection = chooser.getSelectedFile();
        //verify if file exists
        if(selection.exists()){
            //you can continue the code here or call the next method or just use !exists and behavior for wrong file
        }else{
            //System.exit(0), show alert.. etc
        }
    }
porfiriopartida
  • 1,546
  • 9
  • 17
2

Sounds like you want an "Open" behavior, but a confirmation button that says "Save" instead of "Open".

You can do this via this method: http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html#showDialog%28java.awt.Component,%20java.lang.String%29

Pass in "Save" for the approveButtonText argument.

Andrew N Carr
  • 336
  • 1
  • 5
  • Using the setDialogTitle method would allow you to add a hint like the string in Eng.Fouad's answer, but keep the save button label as "Save" using the showDialog method I linked to above. http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html#setDialogTitle%28java.lang.String%29 – Andrew N Carr May 16 '12 at 20:07
2

As simple as this:

JFileChooser fc = new JFileChooser();
while(true)
{
    if(fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION &&
      !fc.getSelectedFile().exists())
        JOptionPane.showMessageDialog(null, "You must select an existing file!");
    else break;
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417