How to get open file popup

2019-05-08 06:59发布

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?

1条回答
成全新的幸福
2楼-- · 2019-05-08 07:27

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();
 } 
查看更多
登录 后发表回答