java - 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,但我不确定如何修复该错误。
解决方案
您必须像这样为文件提供正确的路径,
Scanner a = new Scanner(new File("C:\\data\\c6e1.txt"));
如果将路径指定为 c6e1.txt,则无法识别。如果文件在您的项目、资源目录中,您要么必须提供相对路径,要么像我上面所做的那样考虑提供文件的绝对路径。
推荐阅读
- python - 找到最高的 5 日期返回
- python - 熊猫:添加新列,计算此人达到一天最高分的频率
- java - 错误共享仅支持引导加载程序类是什么意思?
- vhdl - select/when 语句 vhdl 中的多条指令
- flutter - Flutter:在使用 fromJson() 方法解码 json 文件时获取“null”
- regex - 捕获不属于链接的特定单词的所有出现
- performance - 负载较重的 HTTP 服务器中的队列处理
- c - mmap PCIe BAR 和 addr 的打印内容是 ffffffff
- javascript - 你如何在javascript函数参数上传递数组和str和日期?
- javascript - 根据数据属性选择元素