即使文件存在,Java FileNotFoundException也是如此 [英] Java FileNotFoundException even though file exists
问题描述
我正在尝试阅读位于C:\ Users \Siddharth \Documents\aarti \yeh_vidhi_mangal.txt的文件。以下代码表示文件存在
I am trying to read a file located at "C:\Users\Siddharth\Documents\aarti\yeh_vidhi_mangal.txt". Following code indicates that file exists
String filename = "C:\\Users\\Siddharth\\Documents\\aarti\\yeh_vidhi_mangal.txt";
File file = new File(filename);
System.out.println(file.exists());
但是当我尝试使用
FileInputStream in = new FileInputStream(file);
a FileNotFoundException
被抛出。这是因为访问被拒绝了吗?我检查了文件权限,他们没事。
a FileNotFoundException
is thrown. Is this because access is denied? I checked file permissions and they are fine.
我也尝试过没有eclipse的工作。从命令行:
I have also tried working without eclipse. from the command line:
C:\Users\Siddharth\workspace\file_io_test\src>javac Foo.java
Foo.java:16: error: unreported exception FileNotFoundException; must be caught o
r declared to be thrown
FileInputStream in = new FileInputStream(file);
^
1 error
推荐答案
根据 FileInputStream
,如果指定的文件不存在,则是目录而不是常规文件,或由于某些其他原因无法打开阅读然后抛出FileNotFoundException。 (强调我的)文件可能被另一个应用程序锁定或使用。
According to the documentation for FileInputStream
, "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 then a FileNotFoundException is thrown." (emphasis mine) The file may be locked or in use by another application.
file.canRead()
返回?
现在您已经用更多数据更新了问题,我可以看到您误解了错误信息。错误是您正在调用抛出某种类型的异常的方法,并且您没有正确报告或处理异常。您可以为 FileNotFoundException
添加 try
/ catch
或者在方法声明中添加 throws
,声明可以抛出 FileNotFoundException
。
Now that you've updated your question with more data, I can see that you are misinterpreting the error message. The error is that you are calling a method which throws a certain type of exception and you are not properly reporting or handling the exception. You can either add a try
/ catch
for FileNotFoundException
or add a throws
to your method declaration which states that FileNotFoundException
can be thrown.
这篇关于即使文件存在,Java FileNotFoundException也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!