代码
import java.io.*;
import java.util.Scanner;
public class Fileread {
public static void main(String[] args) throws IOException {
File file = new File("List.txt");
String country="india";
int count=countWord(country,file);
System.out.println("The number of students from"+country+" is "+count);
}
public static int countWord(String word, File file) {
int count = 0;
@SuppressWarnings("resource")
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(word))
count++;
}
return count;
}
}
错误:
Exception in thread "main" java.io.FileNotFoundException: List.txt
(The system cannot find the file specified) at
java.io.FileInputStream.open(Native Method) at
java.io.FileInputStream.<init>(Unknown Source) at
java.util.Scanner.<init>(Unknown Source) at
random.Fileread.countWord(Fileread.java:25) at
random.Fileread.main(Fileread.java:17)
答案 0 :(得分:3)
File.txt
是一个相对路径,因此它取决于您的应用程序认为“当前目录”。
为了能够修复这样的错误,请始终使用绝对路径:
File file = new File("List.txt").getAbsoluteFile();
这将告诉系统究竟在哪里查找文件。
下一步是解决问题。修复取决于许多因素,并没有简单的解决方案。