Android Read Text并动态拆分为多维数组

时间:2014-06-06 14:45:52

标签: android arrays file-io multidimensional-array

我读了this thread,但是,如何将文件中的文本动态地放入多维数组?

数据如:

1,4,5,7,nine

11,19

22,twenty-three,39

30,32,38
..
..

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

try {
    ArrayList<List<String> > matrix = new ArrayList<List<String> >();
    FileInputStrem iStream = new FileInputStream("path/to/file");
    BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
    String line = reader.readLine();
    while(line != null){
        line = reader.readLine();
        matrix.add(Arrays.asList(line.split(",")));
    }
} catch (Exception e) {
    // handle exception
} finally {
     reader.close();
     istream.close();
}

ArrayList相对于数组的一个最大优点是ArrayList的大小是动态的,并且它是分摊的常量以添加到最后。

要回答您的评论,请删除:

for (int i = 0; i < matrix.size(); i++) {
    for (int j = 0; j < matrix.get(i).size(); j++) {
        if (someCondition) // determine which to remove
            matrix.get(i).remove(j);
    }
}

答案 1 :(得分:1)

使用BufferedReader之类的类来读取文件中的每一行。在每一行上使用扫描仪来获取单个令牌。

Scanner scanner = new Scanner(currentLineInFile);
scanner.useDelimiter(",");

while (scanner.hasNext())
{
    String token = scanner.next(); // Only call this once in the loop.
    if (token.isEmpty())
    {
        // This case trips when the string "this,is,,a,test" is given.
        // If you don't want empty elements in your array, this is where
        // you need to handle the error.
        continue; // or throw exception, Log.d, etc.
    }
    // Do something with the token (aka. add it to your array structure.
}

如果将其与数组结构相结合,将允许您按需处理数据(例如来自Web服务。)此实现考虑了两个“,”彼此相邻的情况。您可以在阅读时处理这些空元素。使用String.split会将这些空元素留在以后必须处理的数组中。