繁体   English   中英

尝试使用扫描仪读取a.txt文件,但继续获取FileNotFoundException

[英]Trying to read in a.txt file with a scanner but keep getting FileNotFoundException

我不断在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);
}
}

编译并运行.java文件后,它们便成为.class文件,而且我很确定它们的来源位于不同的位置,因此,您仍然需要指定文本文件的位置:

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

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

像这样实例化Scanner

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM