逐行将.txt文件读入ArrayList

时间:2022-04-19 19:25:46

In my latest project i use a .txt file called "atestfile.txt" which resides inside my projects /raw folder, which i created:

在我的最新项目中,我使用名为“atestfile.txt”的.txt文件,该文件位于我创建的projects / raw文件夹中:

逐行将.txt文件读入ArrayList

and this is its content:

这是它的内容:

逐行将.txt文件读入ArrayList

now using these few simple lines of code..

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

逐行将.txt文件读入ArrayList

i want my application to insert the words from the textfile into my ArrayList line by line as seen in this questions awesome first answer.

我希望我的应用程序将文本文件中的单词逐行插入到我的ArrayList中,如本问题中第一个答案所示。

However, no Toast will appear, and even worse, i will receive an IndexOutOfBoundsException for the test.get(3); line i use and the application crashes.

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

I tried all day to get rid of this error but have not succeeded yet in doing so. So since there are a lot of smart people around here and i'd love to learn something about this problem, i thought i'd ask you guys for help first before throwing my computer out of the window.

我整天都试图摆脱这个错误,但还没有成功。所以,因为这里有很多聪明的人,我很想知道这个问题,我想我先请你帮忙,然后把我的电脑扔出窗外。

I'll provide you guys with my error message, copy & pasteable code aswell as my packet structure for some more help on this issue.

我将为您提供我的错误消息,复制和可粘贴的代码以及我的数据包结构,以获得有关此问题的更多帮助。

package com.niklas.cp.citypopulation;

逐行将.txt文件读入ArrayList

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

1 个解决方案

#1


2  

You are calling scanner.nextLine() twice in each loop, but only adding second line to test, thus test will have only three lines.
You have to write like this

您在每个循环中调用scanner.nextLine()两次,但仅添加第二行进行测试,因此测试将只有三行。你必须这样写

while(scanner.hasNextLine()) {
   String s = scanner.nextLine();
   makeToast(s,1);
   test.add(s);
}

If it throws FileNotFoundException try the following

如果它抛出FileNotFoundException,请尝试以下操作

InputStream file = getResources().openRawResource(R.raw.atestfile);
Scanner scanner = new Scanner(file);

#1


2  

You are calling scanner.nextLine() twice in each loop, but only adding second line to test, thus test will have only three lines.
You have to write like this

您在每个循环中调用scanner.nextLine()两次,但仅添加第二行进行测试,因此测试将只有三行。你必须这样写

while(scanner.hasNextLine()) {
   String s = scanner.nextLine();
   makeToast(s,1);
   test.add(s);
}

If it throws FileNotFoundException try the following

如果它抛出FileNotFoundException,请尝试以下操作

InputStream file = getResources().openRawResource(R.raw.atestfile);
Scanner scanner = new Scanner(file);