![](/img/trans.png)
[英]FileNotFoundException cannot be resolved to a type when trying to read a .txt file in java
[英]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.