我在检查文件是否存在于 Java 中时遇到问题。然而 IF block 似乎工作,但 ELSE 似乎不。看,当文件存在时,它会提示一个框,上面写着“找到文件”。只要文件确实存在,就会在我的程序中发生这种情况,问题是当文件不存在时,我的控制台中会出现错误。有人能告诉我什么是更简单和更短的编码我的问题的方法吗?谢谢 !这是我的代码
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
File f = new File(textField.getText());
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
{
JOptionPane.showMessageDialog(null, textField.getText()+" found" );
while ((sCurrentLine = br.readLine()) != null) {
textArea.append(sCurrentLine);
textArea.append(System.lineSeparator());
}
}
else
{
JOptionPane.showMessageDialog(null, textField.getText()+" not found" );
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
最佳答案
问题出在这一行:
br = new BufferedReader(new FileReader(path+f));
您将
File
附加到String
,这是没有意义的。您应该将String
附加到String
,在本例中,textField.getText())
附加到path
。如果文件根据
FileReader
的文档不存在,此行将抛出异常:
Throws:
FileNotFoundException
- if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
这会导致您的程序到达 catch
子句并打印异常堆栈跟踪。您应该只在 f.exists()
返回 true 时调用此行:
if (f.exists())
{
br = new BufferedReader(new FileReader(path + textField.getText()));
...
}
关于java - java判断文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144124/