Search code examples
javafile-iojfilechooseropenfiledialog

How to get open file popup


Right now, I have a set class path, but I want to have an open file pop up and the user chooses which file to open. I've tried JFileChooser, but haven't been successful so far. Here's my code:

public static void main(String[] args) throws IOException {


    JFileChooser chooser = new JFileChooser();

            int returnValue = chooser.showOpenDialog( null ) ;
    if( returnValue == JFileChooser.APPROVE_OPTION ) {
        File file = chooser.getSelectedFile() ;
    }

    // I don't want this to be hard-coded:
    String filePath = "/Users/Bill/Desktop/hello.txt";

How should I go about doing this?


Solution

  • I think the problem is the scope of File file.

    Try Declaring file outside the if-block.

     File file = null;
     if( returnValue == JFileChooser.APPROVE_OPTION ) {
            file = chooser.getSelectedFile() ;
     }
     if(file != null)
     {
          String filePath = file.getPath();
     }