java中的filenotfoundException
时间:2020-02-23 14:34:09 来源:igfitidea点击:
在本教程中,我们将看到Java中的FileNotFoundException。
FileNotFoundException当在指定路径上找不到文件时,由FileInputStream,FileOutputStream,RandomAccessfile的构造抛出。
由于某种原因文件无法访问,也可以提出异常。
例如:当我们没有适当的权限来读取文件。
托运FileNotFoundException是检查异常,因此我们需要通过Java代码处理。
我们应该采取适当的操作来打印给用户的适当异常 FileNotFoundException被抛出。
让我们看一个例子
package org.igi.theitroad;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* FileNotFoundException example
* @author igi
*
*/
public class FileReadExample {
public static void main(String[] args) {
File file = new File("C:/theitroad.txt");
FileInputStream fis = null;
try{
fis = new FileInputStream(file);
while (fis.read()!=-1){
System.out.println(fis.read());
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally{
try{
fis.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
运行上面的程序时,我们将得到以下输出:
java.io.FileNotFoundException: C:/theitroad.txt (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:196) at java.base/java.io.FileInputStream.(FileInputStream.java:139) at org.arpit.theitroad.FileReadExample.main(FileReadExample.java:17) Exception in thread “main" java.lang.NullPointerException at org.arpit.theitroad.FileReadExample.main(FileReadExample.java:27)
正如我们可以看到该路径中未存在的文件,我们正在获取 FileNotFoundException
如何解决filenotfoundException
- 检查是否通过了
file存在于指定文件中 - 检查是否通过了
file实际上是目录 - 由于权限问题,已通过的文件无法打开。我们可能正在尝试写入文件,其中我们只有读取权限。
- 检查已通过的文件名是否不包含任何不可见的字符,例如\ r \ n符号。

