我注意到以下情况:如果我启动应用程序并打开文件,则会出现 JFileChooser
。我尝试写入文件名,但没有收到错误,即使该文件不存在。我得到的是一个文件路径。
JFileChooser fileChooser = new JFileChooser();
int values = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
if (values == JFileChooser.APPROVE_OPTION) {
System.out.println(file.getPath());
} else if (values == JFileChooser.CANCEL_OPTION) {
System.out.println("No file is selected");
} else if (values == JFileChooser.ERROR_OPTION) {
System.out.println("Error!");
} else if (file == null) {
System.out.println("No File is chosen");
}
希望大家能够帮忙。我希望我的问题很清楚,因为我在解释和英语方面遇到问题。
最佳答案
您可以使用 file.exists() 检查文件是否存在。已在 another post 中回答.
文件对象的创建并不能保证您的路径中的文件确实存在。
...
if (values == JFileChooser.APPROVE_OPTION) {
if(file.exists()){
System.out.println(file.getPath());
}else{
System.out.println("file does not exist");
}
}
...
关于java - JFileChooser 检查是否确实选择了文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44936294/