问题描述
我一直在研究一个小程序,并且是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:
解决方法
您的文件夹结构在项目中包含项目。在您的IDE中,如果仅将PA1-WordSearch导入为项目,则它将起作用。
,我希望它对您有用
dictList = dictRead(“ ./ FileFolder / aaa.txt”);
,该文件不在Java期望的位置。
TestCases/dictionary.txt
是相对路径。要在驱动器上找到文件,它会相对于某些“工作目录”进行解释。您可能会在运行配置中找到它。
但是,使用绝对路径指定文件更为健壮,该路径以C:\
开头或类似(如果您使用的是Windows计算机)。使用绝对路径使您独立于工作目录。
因此:使用Windows资源管理器找到文件的绝对路径,并将该路径作为参数插入运行配置中。