【问题标题】:Trying to read in a.txt file with a scanner but keep getting FileNotFoundException尝试使用扫描仪读取 .txt 文件,但不断收到 FileNotFoundException
【发布时间】:2014-12-05 10:28:13
【问题描述】:

我不断收到 java 中的 FileNotFoundException。我的文件名与 .txt 扩展名完全相同,并且 .txt 文件与我的 .java 文件位于同一文件夹中。我不确定这里发生了什么,我尝试了多种方法。

这是我的主类,我尝试通过调用命令类来打印带有索引号的每个命令。

public class mainClass {
  public static void main(String[] args) throws Exception {
      commands fileCommands = new commands();
      for (int i = 0; i >= fileCommands.getLength() - 1; i++) {
            System.out.println("" + i + ": " + fileCommands.getCommand(i));
        }

这里是命令类。

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

public class commands {

ArrayList<String> commandList;

public Commands() throws Exception {
    this.commandList = new ArrayList<>();

    try {
        Scanner s = new Scanner(new File("commands.txt"));

            while(s.hasNextLine()) {
                commandList.add(s.nextLine());
            }

    } catch (FileNotFoundException ex) {
        System.out.println(ex);
    }
 }


public int getLength() {
    return commandList.size();
}

public String getCommand(int pIndex) throws IllegalArgumentException {
    return commandList.get(pIndex);
}
}

【问题讨论】:

  • 谢谢!我现在让扫描仪工作并读取文件。我已经对其进行了调试,并看到它将每个命令都放入了数组列表中。现在 main 方法中的 for 循环根本不打印了。

标签: java java.util.scanner filenotfoundexception readfile


【解决方案1】:

当它编译并运行时,.java 文件变成了.class 文件,我很确定它们的来源在不同的位置,因此您仍然需要指定文本文件的位置:

Scanner s = new Scanner(new File("path-to-text-file/commands.txt"));

【讨论】:

    【解决方案2】:

    您应该避免像这样加载文件。这在多种情况下都不起作用。

    像这样实例化Scanner

    Scanner s = new Scanner(commands.class.getResourceAsStream("commands.txt"));
    

    附注:Java 中类的命名约定是名称应以大写字母开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      相关资源
      最近更新 更多