始终接收FileNotFoundException,即使文件在SRC文件夹中也是如此

时间:2017-07-15 01:22:35

标签: java file exception file-io

我目前正在尝试编写一个逐行读取文件并将每行添加到arrayList的程序。我的另一个函数应该对该缓冲区中的项进行排序,然后将它们写入文本文件。但是,即使我的文件位于src目录中,以及带有.class文件的目录,我仍然会收到FileNotFoundException。我的代码如下

public static ArrayList<String> readDictionary(String filename, 
ArrayList<String> buffer) throws IOException, FileNotFoundException {
    File f = new File(filename);
    Scanner fileIn = new Scanner(f);
    //Scanner fileIn = new Scanner(new File(filename));
    boolean add = true;

    while (fileIn.hasNextLine() == true) {
        for (String s : buffer) {
            if (fileIn.nextLine().equals(s)) {
                add = false;
            }
        }
        if (add == true) {
            buffer.add(fileIn.nextLine());
        }
        add = true;
    }
    fileIn.close();
    return buffer;
}

public static void writeDictionary(String filename, ArrayList<String> buffer) throws IOException, FileNotFoundException {
    File f = new File(filename);
    Collections.sort(buffer, String.CASE_INSENSITIVE_ORDER);
    Path file = Paths.get(filename);
    Files.write(file, buffer);
}

public static void main(String[] args) throws IOException, FileNotFoundException{
    ArrayList<String> buffer = new ArrayList<>();
    readDictionary("inputtest.txt", buffer);
}

Exception in thread "main" java.io.FileNotFoundException: inputtest.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 UltimateDictionary.readDictionary(UltimateDictionary.java:18)
at UltimateDictionary.main(UltimateDictionary.java:46)

我通过将filename设置为“inputtest.txt”来测试此程序,并且该文件位于我的src目录中,带有.java文件,但它仍然会抛出错误。另外,我该如何关闭文件? f.close()给了我一个错误。

1 个答案:

答案 0 :(得分:-1)

src或.class目录中的文件,只能表示文件在classpath中,而新文件(filename);搜索当前的工作目录。要搜索类路径,请在File f = new File(filename)之后更改readDictionary方法;添加:

    if (!f.exists()) {
        URL url = <yourclassname>.class.getResource(filename);
        if (url != null)
            f =  new File(url.getPath());
    }

你必须使用yourclassname.class,因为该方法是静态的。也应该工作:

if (url == null)
    url = ClassLoader.getSystemResource(filename);