我试图使用绝对路径从文件系统读取文件,但因为“FileNotFoundException”失败了,我不知道原因。
File file=new File("E:\\Directory\\File.txt");
byte[] buff=new byte[8];
FileInputStream fileIn=new FileInputStream(file.getAbsolutePath());
int n=fileIn.read(buff);
System.out.println(n);
我试图使用绝对路径从文件系统读取文件,但因为“FileNotFoundException”失败了,我不知道原因。
File file=new File("E:\\Directory\\File.txt");
byte[] buff=new byte[8];
FileInputStream fileIn=new FileInputStream(file.getAbsolutePath());
int n=fileIn.read(buff);
System.out.println(n);
以下是可能导致此问题的一些原因:
目录和文件存在,但您使用的真实路径名或路径名存在问题:
实际错误发生在代码的其他地方。
我也可以建议您尝试像这样:
File file = new File("E:/Directory/File.txt");
FileInputStream fileIn = new FileInputStream(file);
file
已经表示绝对路径,因此不需要调用file.getAbsolutePath()
。问题就像错误所述:
文件不存在,即在该路径中没有文件。您给构造函数的名称可能是错误的。 您可以通过以下方式检查文件是否存在:
File file=new File("E:\\Directory\\File.txt");
if(file.exists()){
//do things here
}
你也可以从Windows资源管理器中检查文件是否存在(假设你的电脑运行的是Windows操作系统)。如果你找不到该文件,那么这就解释了问题所在。正如我所说,错误是因为该路径下没有文件而引发的。
file.exists()
是否返回true? - ItamarG3