android - 读取文本文件并将数据填充到数组中。

标签 android text-files filereader

我很确定我只是在问一个愚蠢的问题但是,只是说有一个包含这些数据的 txt 文件

UniPub;112 Binara St;ACT
MooseHeads;科恩街 54 号;ACT
立方体;莫森街 24 号;ACT

我将使用以下代码在我的应用程序中读取它:

package au.edu.canberra.g30813706;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.os.Environment;


public class FileReader extends Activity{{

    ArrayList<String> sInfo = new ArrayList<String>();

    String txtName = "AccomodationTxt.txt";
    File root = Environment.getExternalStorageDirectory();
    File path = new File(root, "CanberraTourism/" + txtName);

    try {

        BufferedReader br = new BufferedReader (
                            new InputStreamReader(
                            new FileInputStream(path)));
        String line;
        String[] saLineElements;
        while ((line = br.readLine()) != null)
        {
            //The information is split into segments and stored into the array
            saLineElements = line.split(";");
            for (int i = 0; i < saLineElements.length; i++) 
                  sInfo.add(saLineElements[i]);
            //sInfo.addAll(Arrays.asList(saLineElements[0], saLineElements[1], saLineElements[3]));     
        }
         br.close();


    } 
    catch (FileNotFoundException e) {

        System.err.println("FileNotFoundException: " + e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }}
}

我如何区分数组中的行?

例如

我想在一页上显示名字的文本,所以只有

UniPub
驼鹿头
立方体

最佳答案

如何将字符串数组而不是单个元素添加到 ArrayList。
像这样:

ArrayList<String[]> sInfo = new ArrayList<String[]>();
String line;
String[] saLineElements;
while ((line = br.readLine()) != null)
{
    //The information is split into segments and stored into the array
    saLineElements = line.split(";");
        sInfo.add(saLineElements);
}

然后您可以遍历 sInfo 并使用 sInfo 中每个数组中的第一个元素。

关于android - 读取文本文件并将数据填充到数组中。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16338062/

相关文章:

android - 将动态字符串数组添加到android中的动态 ListView

c - 使用文件和列表修改 C 中的字符

c - 读入文本文件 - 一次 1 个字符。使用 C

java - 读取无空格整数的文件 - hasNextInt() 永远不会返回 true

android - Drawable 的 mutate 方法 Android 1.6 中的 NullPointerException

java - 编译器是否优化了不添加/覆盖方法的匿名类?

android - 有没有办法从 Google Play 上的开发者那里获取所有应用程序

c# - 写入文本文件 C#

javascript - FileReader 和 $scope.$watch 的 AngularJS 问题?

java - 如何使用 BufferedReader 将行放入 ArrayList 中然后执行它们?