逐行读取一个.txt文件到ArrayList

Read a .txt file into ArrayList line by line

在我最新的项目中,我使用了一个名为 "atestfile.txt" 的 .txt 文件,它位于我的项目 /raw 中我创建的文件夹:

这是它的内容:

现在使用这几行简单的代码..

我希望我的应用程序将文本文件中的单词逐行插入到我的 ArrayList 中,如 this questions awesome first answer.

中所示

但是,不会出现 Toast,更糟糕的是,i 将收到 test.get(3);[=45 的 IndexOutOfBoundsException =] 我使用的行和应用程序崩溃。

我整天都在尝试摆脱这个错误,但还没有成功。 因此,由于这里有很多聪明人,而且我很想了解有关这个问题的一些知识,所以我想在将我的计算机从 window 中扔出去之前,我会先向你们寻求帮助。

我会向你们提供我的错误消息、复制和粘贴代码以及我的数据包结构,以获得有关此问题的更多帮助。

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);