【问题标题】:Read Text file and fill the data in Array.读取文本文件并将数据填充到数组中。
【发布时间】:2013-05-02 12:27:50
【问题描述】:

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

UniPub;112 Binara St;ACT
MooseHeads;54 Cohen St;ACT
立方体;24 Mawson St;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
驼鹿头
立方体

【问题讨论】:

  • 您是否总是将三个值以first_val;second_val;third_val 格式存储在文件中?
  • 您的代码当前是否对字符串输入进行任何拆分?
  • 为什么不将行存储在一个数组中,当需要时可以拆分行并使用信息?这样,您将为每一行分隔所有信息。还是有必要一开始就分开?
  • 它实际上是 5 个值,上面只有一个例子而且我还没有测试它,因为我不确定它是否会起作用,所以这就是我问这个问题的原因

标签: android text-files filereader


【解决方案1】:

如何将字符串数组添加到 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 中每个数组中的第一个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多