Java 试图用扫描仪读取.txt文件,但一直获取FileNotFoundException
我一直在用java获取FileNotFoundException。我的文件名与.txt扩展名完全相同,.txt文件与.java文件位于同一文件夹中。我不确定这里发生了什么,我已经尝试了很多方法 这里是我的主类,我试图通过调用commands类来打印每个带有索引号的命令Java 试图用扫描仪读取.txt文件,但一直获取FileNotFoundException,java,java.util.scanner,filenotfoundexception,readfile,Java,Java.util.scanner,Filenotfoundexception,Readfile,我一直在用java获取FileNotFoundException。我的文件名与.txt扩展名完全相同,.txt文件与.java文件位于同一文件夹中。我不确定这里发生了什么,我已经尝试了很多方法 这里是我的主类,我试图通过调用commands类来打印每个带有索引号的命令 public class mainClass { public static void main(String[] args) throws Exception { commands fileCommands =
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);
}
}
这是commands类
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 s = new Scanner(commands.class.getResourceAsStream("commands.txt"));
请注意:Java中类的命名约定是名称应以大写字母开头。谢谢!我已经让扫描仪工作了,正在读取文件。我已经对它进行了调试,看到它将每个命令都放在arraylist中。现在,主方法中的for循环根本不打印。