Fiery Phoenix
Fiery Phoenix

Reputation: 1166

JFileChooser Returns FileNotFoundException

More specifically, it does work, but ONLY if I choose a file that exists in the source folder where my program and its resources are. When I move a file to, say, the desktop or My Documents and try to read it from there, I get a FileNotFoundException.

Here is my code:

private void btnBrowseFileActionPerformed(java.awt.event.ActionEvent evt) {                                              
    JFileChooser myFileChooser = new JFileChooser();
    int rVal = myFileChooser.showOpenDialog(Singlelayer.this);
    if (rVal == JFileChooser.APPROVE_OPTION) {
        txtFile.setText(myFileChooser.getSelectedFile().getName());
    }
}

As you can see, it is attached to a "Browse..." button, so it is part of a GUI. But that's beside the point.

It doesn't work with any file that isn't in the project folder with the other source files. Not entirely sure what's going on but any help would be appreciated.

Upvotes: 1

Views: 810

Answers (2)

Ahsan
Ahsan

Reputation: 29

you need to use the getPath() of File class object which is return by myFileChooser.getSelectedFile() statement.

eg
  File file = myFileChooser.getSelectedFile();
  String path = file.getPath();
  String name = file.getName();

now used these path , name variables .

Upvotes: 0

Maroun
Maroun

Reputation: 95958

You're using the file name:

txtFile.setText(myFileChooser.getSelectedFile().getName());

Which returns the file's name. So it only recognize files that are in the source folder.

Instead, you should use the file path.

Upvotes: 3

Related Questions