java-FileNotFoundException即使指定文件存在

时间:2018-06-26 02:15:37

标签: 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,我不确定如何解决该错误。

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:-1)

Scanner a = new Scanner(new File("c6e1.txt"));

仅当“ .txt”文件位于“ .java”文件所在的位置时,Java才会接受它。在其他情况下,您必须将“ .txt”文件的完整位置(路径)提到为(“ C:(folder \ c6e1.txt”)

答案 2 :(得分:-2)

您应该为该文件提供完全限定的名称。 例如: 系统D中的文件:驱动器 D:/下载/文件名.txt

相关问题