【问题标题】:Fixing file not found exception in Java [closed]在Java中修复文件未找到异常[关闭]
【发布时间】:2020-09-09 07:26:44
【问题描述】:

我一直在开发一个小程序,而且我是 Java 新手。但它不断引发 filenotfound 异常。 这是我的代码:

import java.io.FileNotFoundException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/* 
 * Don't forget your file header comment here!
 */

public class WordSearch {
    /*
     * This is how you declare constants in Java. You can now type
     * 'MIN_WORD_LENGTH' anywhere you want to refer to it.
     */
    private static final int MIN_WORD_LENGTH = 3;

    public static void main(String[] args) throws FileNotFoundException {
        // Remember, to access command-line arguments, you use args[0],
        // args[1],...
        // See CommandLine.java and Stdin.java in the Class Examples github for examples.
        List<String> dictList= new ArrayList<>();
        dictList = dictRead(args[0]);
    }
    public static List<String> dictRead (String filePath) throws FileNotFoundException{
        Scanner dictScan = null;
        dictScan = new Scanner(new File(filePath));
        List<String> dictList = new ArrayList<>();
        int i=0;
        while (dictScan.hasNext()) {
            dictList.add(i, dictScan.nextLine());
            i+=1;
        }
        return dictList;
    }

}

这我不知道为什么我不断收到这个异常。我更改了运行配置并将 TestCases/dictionary.txt 作为我的第一个参数。

这是我的目录图片,我正在运行 WordSearch.java:

【问题讨论】:

    标签: java eclipse filenotfoundexception


    【解决方案1】:

    您的文件夹结构在项目中有项目。在您的 IDE 中,如果您仅将 PA1-WordSearch 作为项目导入,它将起作用。

    【讨论】:

      【解决方案2】:

      希望对你有用

      dictList = dictRead("./FileFolder/aaa.txt");

      【讨论】:

        【解决方案3】:

        文件不在 Java 期望的位置。

        TestCases/dictionary.txt 是相对路径。要在驱动器上查找文件,它会相对于某个“工作目录”进行解释。您可能可以在运行配置中找到它。

        但是使用绝对路径指定文件更为可靠,如果您在 Windows 计算机上,则以 C:\ 或类似名称开头。使用绝对路径使您独立于工作目录。

        所以:使用 Windows 资源管理器找到文件的绝对路径,并将该路径作为参数插入到运行配置中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多