首页 > 解决方案 > java - FileNotFoundException 即使指定的文件存在

问题描述

我的 CS 课被分配了以下作业:

编写一个名为 boyGirl 的方法,该方法接受一个 Scanner,该 Scanner 从包含一系列名称和整数的文件中读取其输入。名字在男孩名字和女孩名字之间交替出现。您的方法应该计算男孩整数之和与女孩整数之和之间的绝对差。

这是我的代码:

import java.io.*;
import java.util.*;
public class Chapter_6_Exercises
{
    public static void main(String[] agrs)
                        throws FileNotFoundException {
        Scanner a = new Scanner(new File("c6e1.txt"));
        boyGirl(a);
    }

    public static void boyGirl(Scanner input)
                       throws FileNotFoundException {
        int boySum = 0;
        int girlSum = 0;
        int count = 0;
        int sumDifference = 0;
        while(input.hasNextInt()) {
           count++;
           if(count%2 == 0) {
              girlSum += input.nextInt();     
           } else {
              boySum += input.nextInt();    
           }
        }
        sumDifference = Math.abs(boySum-girlSum);
        System.out.println("boySum = " + boySum);
        System.out.println("girlSum = " + girlSum);
        System.out.println("Difference between boys' and girls' ");
        System.out.println("sums is " + sumDifference);
    }
}

该代码编译文件,但是当我尝试运行它时,出现以下错误:

java.io.FileNotFoundException: c6e1.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.util.Scanner.<init>(Scanner.java:611)
    at Chapter_6_Exercises.main(Chapter_6_Exercises.java:7)

但是,我已经创建了文件 c6e1.txt,但我不确定如何修复该错误。

标签: javafilenotfoundexception

解决方案


您必须像这样为文件提供正确的路径,

Scanner a = new Scanner(new File("C:\\data\\c6e1.txt"));

如果将路径指定为 c6e1.txt,则无法识别。如果文件在您的项目、资源目录中,您要么必须提供相对路径,要么像我上面所做的那样考虑提供文件的绝对路径。


推荐阅读