本文介绍了即使文件存在并且拼写正确,也获取FileNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个小程序,该程序将读取一个文本文件,该文件包含许多随机生成的数字,并产生诸如均值,中位数和众数之类的统计信息.我已经创建了文本文件,并确保在声明为新文件时名称完全相同.

I'm creating a small program that will read a text file, which contains a lot of randomly generated numbers, and produce statistics such as mean, median, and mode. I have created the text file and made sure the name is exactly the same when declared as a new file.

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

Yes, the file is in the same folder as the class files.

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)

推荐答案

如何添加:

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

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

Print this out. It will tell you what the current working directory is. Then you should be able to see why it isn't finding the file.

您可以检查是否允许自己执行某些操作(如果找不到该文件),而不是抛出代码:

Rather than allowing your code to throw, you could check to allow yourself to do something if the file isn't found:

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

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

Please run the below and paste the output:

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());

这篇关于即使文件存在并且拼写正确,也获取FileNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 14:26
查看更多