文本文件-Java FileReader出现问题



你好,我的代码中有这个

File file = new File("words.txt");
    Scanner scanFile = new Scanner(new FileReader(file));
    ArrayList<String> words = new ArrayList<String>();
    String theWord;    
    while (scanFile.hasNext()){
        theWord = scanFile.next();
        words.add(theWord);
    }

但出于某种原因,我得到了

java.io.FileNotFoundException

我把words.txt文件和我所有的.java文件放在同一个文件夹中

我做错了什么?谢谢

提示:将这一行添加到代码中。。。

System.out.println(file.getAbsolutePath());

然后将该路径与文件的实际位置进行比较。问题应该会立即显现出来。

文件应位于执行应用程序的目录中,即工作目录

通常,将数据文件与代码打包是个好主意,但使用java.io.File读取它们是个问题,因为很难找到它们。解决方案是使用java.lang.ClassLoader中的getResource()方法将流打开到文件。这样,ClassLoader就可以在代码存储的位置查找文件,无论它在哪里。

try:

URL url = this.getClass().getResource( "words.txt" );
File file = new File(url.getPath());

您尚未指定绝对路径。因此,该路径将被视为相对于进程的当前工作目录的路径。通常,这是您启动Main Class的目录。

如果您不确定工作目录的位置,可以使用以下片段打印出来:

System.out.println(System.getProperty("user.dir"));

要解决此问题,需要在原始路径中添加必要的目录来定位文件。

最新更新