即使文件存在且拼写正确,也会获取FileNotFoundException

我正在创建一个小程序,它将读取一个文本文件,其中包含大量随机生成的数字,并生成统计数据,如均值,中位数和模式。 我创建了文本文件,并确保在声明为新文件时名称完全相同。

是的,该文件与类文件位于同一文件夹中。

public class GradeStats { public static void main(String[] args){ ListCreator lc = new ListCreator(); //create ListCreator object lc.getGrades(); //start the grade listing process try{ File gradeList = new File("C:/Users/Casi/IdeaProjects/GradeStats/GradeList"); FileReader fr = new FileReader(gradeList); BufferedReader bf = new BufferedReader(fr); String line; while ((line = bf.readLine()) != null){ System.out.println(line); } bf.close(); }catch(Exception ex){ ex.printStackTrace(); } } 

}

错误行内容如下:

 java.io.FileNotFoundException: GradeList.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:138) at java.io.FileReader.(FileReader.java:72) at ListCreator.getGrades(ListCreator.java:17) at GradeStats.main(GradeStats.java:11) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) 

如何添加:

 String curDir = System.getProperty("user.dir"); 

打印出来。 它会告诉你当前的工作目录是什么。 然后你应该能够看到它为什么找不到文件。

如果找不到文件,您可以检查以允许自己做某事,而不是允许您的代码抛出:

 File GradeList = new File("GradeList.txt"); if(!GradeList.exists()) { System.out.println("Failed to find file"); //do something } 

请运行以下内容并粘贴输出:

 String curDir = System.getProperty("user.dir"); File GradeList = new File("GradeList.txt"); System.out.println("Current sys dir: " + curDir); System.out.println("Current abs dir: " + GradeList.getAbsolutePath()); 

问题是您只指定了相对文件路径,并且不知道您的Java应用程序的“当前目录”是什么。

添加此代码,一切都将清楚:

 File gradeList = new File("GradeList.txt"); if (!gradeList.exists()) { throw new FileNotFoundException("Failed to find file: " + gradeList.getAbsolutePath()); } 

通过检查绝对路径,您将发现该文件不是当前目录。

另一种方法是在创建File对象时指定绝对文件路径:

 File gradeList = new File("/somedir/somesubdir/GradeList.txt"); 

顺便说一句,尝试坚持命名约定:使用前导小写字母命名变量,即gradeList而不是GradeList