rogerdpack
rogerdpack

Reputation: 66741

java file chooser that forces the file to already exist

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.

Upvotes: 3

Views: 2616

Answers (3)

Eng.Fouad
Eng.Fouad

Reputation: 117587

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;
}

Upvotes: 2

porfiriopartida
porfiriopartida

Reputation: 1556

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
        }
    }

Upvotes: 3

Andrew N Carr
Andrew N Carr

Reputation: 346

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.

Upvotes: 2

Related Questions