【发布时间】: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