Read Text file and fill the data in Array.

2019-08-08 17:04发布

Im pretty sure im just asking a silly question but, jut say in have a txt file that has this data on it

UniPub;112 Binara St;ACT
MooseHeads;54 Cohen St;ACT
Cube;24 Mawson St;ACT

Ill read it in my application using this code:

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

How would i differentiate the lines in the Array?

For example

I would want to display the text of the names on one page, so only

UniPub
MooseHeads
Cube

1条回答
家丑人穷心不美
2楼-- · 2019-08-08 17:31

What about adding the String arrays to the ArrayList instead of the individual elements.
Like this:

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

Then you could loop through sInfo and use the first element in each array in sInfo.

查看更多
登录 后发表回答