lrv*_*ius 4 java file-io jfilechooser openfiledialog
现在,我有一个设置类路径,但我想弹出一个打开的文件,用户选择打开哪个文件.我已经尝试过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";
Run Code Online (Sandbox Code Playgroud)
我应该怎么做呢?
我认为问题的范围是File file.
尝试file在if-block之外声明.
File file = null;
if( returnValue == JFileChooser.APPROVE_OPTION ) {
file = chooser.getSelectedFile() ;
}
if(file != null)
{
String filePath = file.getPath();
}
Run Code Online (Sandbox Code Playgroud)