我对Java很新,并试图扫描.txt文件以从中检索单个单词。文本文件扫描仪无法将元素添加到ArrayList
我在哪里弄错了,因为没有元素被添加到ArrayList?
public class ScanInputFile {
public static ArrayList<String> list = new ArrayList<String>();
public static void importArrayList(String path) throws FileNotFoundException {
File textFile = new File(path);
Scanner s = new Scanner(textFile);
while (s.hasNext()){
list.add(s.next());
}
s.close();
}
public static void main(String[] args) throws FileNotFoundException {
importArrayList("C:\\MyFirstList.txt");
System.out.println(list.get(0));
}
}
这抛出即使TXT文件包含10个字,每行2个字的IndexOutOfBounds异常。
在遇到FileNotFoundExceptions问题时,我确保path.exists()和path.canRead()返回true。
感谢您的帮助!
你调试过'hasNext()'是否为'true'至少一次? – Smutje
显示完整的错误 –
是的,我做到了。如下所示,直到替换txt文件,它从未返回true。 – Sp33dyGonzal3s