如何获取打开文件弹出窗口

现在,我有一个设置类路径,但我想弹出一个打开的文件,用户选择打开哪个文件。 我已经尝试过JFileChooser,但到目前为止还没有成功。 这是我的代码:

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

我该怎么做呢?

我认为问题是File file的范围。

尝试在if-block之外声明file

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