Android动态读取文本并分割成多维数组



我读这个线程,但是,我怎么能把文本从一个文件动态到多维数组?

数据:

1,4,5,7,nine
11,19
22,twenty-three,39
30,32,38
..
..

你可以这样做:

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相对于array的最大优点之一是,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);
    }
}

使用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服务)。这个实现解释了两个相邻的","的情况。您可以在读取这些空元素时处理它们。使用字符串。Split将把这些空元素留在数组中,稍后再处理。

相关内容

  • 没有找到相关文章

最新更新