在我当前的项目中,我遇到了未收到文件未找到异常的问题。我的驱动程序文件将要打开的路径传递给正在构建图书库的构造函数。我正在使用 JFileChooser 来获取路径。在尝试强制错误(输入不存在的文件名)时,它会构建其中没有信息的库,并且不会引发错误。
驱动程序代码:
//open an existing library
JFileChooser dlg = new JFileChooser ("LibraryData");
FileNameExtensionFilter filter = new FileNameExtensionFilter ("Text Files", "txt");
dlg.setFileFilter(filter);
dlg.setDialogTitle("Select Existing File");
dlg.setApproveButtonToolTipText("Select the file you want to open and click me.");
int button = dlg.showOpenDialog(null);
if (button == dlg.APPROVE_OPTION)
{
currentPath = dlg.getSelectedFile().getPath();
library = new PersonalLibrary(currentPath);
System.out.println("===========================================================");
System.out.println("File opened successfully from: \n" + currentPath);
System.out.println("===========================================================");
}
Util.enterToContinue();
Util.clearScreen();
break;
库代码:
public PersonalLibrary(String path)
{
try
{
File myFile = new File(path);
if (myFile.exists())
{
Scanner input = new Scanner(myFile);
while(input.hasNext())
{
//code that populates the library
}
input.close();
saveNeeded = false;
}
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
最佳答案
您检查文件是否存在的 catch block 将永远不会被执行。
if(myFile.exists())
如果它不存在,则不会执行任何其他操作,包括 catch block 。此代码块中不能发生 FileNotFoundException。如果您想捕获 FileNotFoundException,请摆脱 if block 。或者只是添加一个 else block ,然后在文件不存在时执行您想要执行的任何处理。
关于Java FileNotFoundException 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26660456/