3

I noticed the following: If I start my application and go to open a file, then the JFileChooser appears. I tried writing a filename and I did not get an error, even though the file does not exist. What I get is a file path.

 JFileChooser fileChooser = new JFileChooser();
    int values = fileChooser.showOpenDialog(null);
    File file = fileChooser.getSelectedFile();

    if (values == JFileChooser.APPROVE_OPTION) {
        System.out.println(file.getPath());
    } else if (values == JFileChooser.CANCEL_OPTION) {
        System.out.println("No file is selected");
    } else if (values == JFileChooser.ERROR_OPTION) {
        System.out.println("Error!");
    } else if (file == null) {
        System.out.println("No File is chosen");
    }

I hope you guys can help. I hope my question is clear because I have problems with explanations and with the English language.

cello
  • 5,356
  • 3
  • 23
  • 28
TobiasDex
  • 63
  • 7

1 Answers1

1

you can check if a file exists with: file.exists(). Already answered in another post.
The creation of a file object does not garuantee that a file at your path does exist.

...
if (values == JFileChooser.APPROVE_OPTION) {
    if(file.exists()){
        System.out.println(file.getPath());
    }else{
        System.out.println("file does not exist");
    }
}
...
F. Fritz
  • 69
  • 5
  • Sorry I dont find this post. I try it out – TobiasDex Jul 05 '17 at 21:33
  • It work but I get the statement of values==JFileChooser.APPROVE_OPTION why? – TobiasDex Jul 05 '17 at 21:38
  • 1
    JFileChoose just let you pick any path. If it was a succesfull selection of a path, then it is "approved". Succes for the JFileChooser does not mean that the slected file also exists. What if you want to select a non existend file, because you want to save something? – F. Fritz Jul 05 '17 at 21:41