在我最新的项目中,我使用了一个名为 “atestfile.txt” 的 .txt 文件,它位于我创建的项目/raw 文件夹中:
这是它的内容:
现在使用这几行简单的代码..
我希望我的应用程序逐行将文本文件中的单词插入我的 ArrayList,如 this questions awesome first answer. 中所示
但是,不会出现任何 Toast,更糟糕的是,我将收到我使用的 test.get(3); 行的 IndexOutOfBoundsException 并且应用程序崩溃。
我一整天都在尝试摆脱这个错误,但还没有成功。 因此,既然这里有很多聪明人,而且我很想了解这个问题,我想我会先向你们寻求帮助,然后再把我的电脑扔出窗外。
我会向你们提供我的错误消息、复制和粘贴代码以及我的数据包结构,以获得有关此问题的更多帮助。
package com.niklas.cp.citypopulation;
final ArrayList<String> test = new ArrayList<String>();
try {
Scanner scanner = new Scanner(new File("android.resource:// com.niklas.cp.citypopulation/raw/atestfile.txt"));
while(scanner.hasNextLine()){
makeToast(scanner.nextLine(),1);
test.add(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String abc = test.get(3);
tv_highscore.setText(abc);
最佳答案
您在每个循环中调用了 scanner.nextLine() 两次,但只将第二行添加到 test
,因此 test
将只有三行。
你必须这样写
while(scanner.hasNextLine()) {
String s = scanner.nextLine();
makeToast(s,1);
test.add(s);
}
如果它抛出 FileNotFoundException,请尝试以下操作
InputStream file = getResources().openRawResource(R.raw.atestfile);
Scanner scanner = new Scanner(file);
关于java - 逐行读取一个.txt文件到ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52933140/