5

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

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

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.<init>(FileInputStream.java:138)
    at java.io.FileReader.<init>(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)
4

2 回答 2

11

如何添加:

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());
于 2012-05-29T01:20:05.883 回答
2

问题是您只指定了一个相对文件路径并且不知道您的 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");

顺便说一句,尽量坚持命名约定:用前导小写字母命名变量,即gradeListGradeList

于 2012-05-29T01:29:09.647 回答