繁体   English   中英

逐行将.txt文件读入ArrayList

[英]Read a .txt file into ArrayList line by line

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

文件位置

这是它的内容:

文件内容

现在使用这些简单的代码行。

码

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

但是,没有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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM