0

代码

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)

4

1 回答 1

3

File.txt是一个相对路径,所以它取决于您的应用程序认为的“当前目录”。

为了能够修复这样的错误,请始终使用绝对路径:

File file = new File("List.txt").getAbsoluteFile();

这将告诉系统在哪里寻找文件。

下一步是解决问题。修复取决于许多因素,并且没有简单的解决方案。

于 2013-11-12T14:52:42.797 回答