Read and split text file into an array - Android

前端 未结 4 791
说谎
说谎 2020-12-22 05:07

I have gone through loads of these questions but still cant seem to figure it out. I have a text file split into rows. Each row consists of 5 pieces of data separated by a \

相关标签:
4条回答
  • 2020-12-22 05:19

    You could use a BufferedReader to read each line and then split the line using the .split(','); method.

    Some pseudo code:

    BufferedReader bfr = new BufferedReader(InputStreamReader/FileReader...);
    String line = null;
    int index = 0;
    String [][] xyz = new String [100][5];
    
    while ( (line = bfr.readLine()) != null) {
        if (index < xyz.length) xyz[index] = line.split(",");
        index++;
    }   
    

    Hope this helped!

    0 讨论(0)
  • 2020-12-22 05:25
    /* Assuming you want a 5 by n matrix from this data
    John,22,1953,Japan,Green
    Anna,18,2012,Mexico,Blue
    Sam,34,1976,San Francisco,Pink
    .
    .
    .
    .
    nth row
    
    String[] row = s.split(","); */
    for (int i = 0; i<n i++)
    {
        for(int j = 0; j<originalString.length; j++)
        {
            xyz[i] = originalString[j].split(",");
        }
    }
    
    0 讨论(0)
  • 2020-12-22 05:30

    See Using BufferedReader.readLine() in a while loop properly for an example of reading a file line by line using a buffered reader, then combine this with Kon's answer and I think you have a solution.

    AssetManager manger;
    String line = null;
    List<String[]> xyzList = new ArrayList<String[]>();
    String[][] xyz;  
    InputStream is;
    InputStreamReader isr;
    BufferedReader br;
    try {
        manger = getAssets();
        is = manager.open("data.txt");
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        while ((line = br.readLine()) != null) {
          xyzList.add(line.split(","));
        }
        xyz = (String[][])xyzList.toArray();
    }catch (IOException e1) {
        Toast.makeText(getBaseContext(), "Problem!", Toast.LENGTH_SHORT).show();
    }finally{
        br.close();
        isr.close();
        is.close();
    }
    
    0 讨论(0)
  • 2020-12-22 05:34

    I assume you understand the basics of reading through a file. So let's start at where you have your String s equal to one full row:

    String s = "John,22,1953,Japan,Green";
    

    You can call the split() function to return an array from s subdivided by some expression (in this case, a comma) like so:

    String[] row = s.split(","); //Returns a new String array {John,22,1953,Japan,Green}
    

    Then you have row[0] = "John", row[1] = 22, and so on. You can do whatever you would like with these arrays, including store them in a multidimensional array if that's what you want to do.

    String[][] xyz = new String[numRows][5];
    xyz[0] = row;
    System.out.println(xyz[0][0]); //prints "John"
    

    Hopefully that's clear and I understood what you were trying to do correctly.

    0 讨论(0)
提交回复
热议问题