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0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
我已经尝试过了:
ArrayList<ArrayList<Integer>> multi=new ArrayList();
ArrayList<Integer> line=new ArrayList();
AssetManager assetManager = getAssets();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(assetManager.open("level/world1/w1-1.txt"), "UTF-8"));
String mLine = reader.readLine();
while (mLine != null) {
mLine = reader.readLine();
}
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
但我不知道如何将我的mLine放入我的多阵列中:/
感谢您的帮助! :)
答案 0 :(得分:1)
看起来您已经编写了正确读取文件的代码,所以您的问题实际上是关于如何将逗号分隔的String
解析为一系列Integer
对象并存储它们在List
中以有效的方式。
Java已经有了很好的工具来进行简单的文本解析,在这种情况下使用Scanner似乎很合适。
为你的内循环尝试这样的事情:
while (mLine != null) {
Scanner sc = new Scanner(mLine); // create a Scanner for each line
sc.useDelimiter(","); // parse the line for tokens delimited by commas
ArrayList<Integer> inner = new ArrayList<>();
while (sc.hasNextInt()) {
inner.add(sc.nextInt()); // add each number found to the inner list
}
multi.add(inner); // add the inner list to the outer list
sc.close();
mLine = reader.readLine();
}
请注意,Scanner
允许您设置要解析的分隔符,并且具有它知道的几个内置类型,因此您不需要进行任何中间String
创建或者输入。
答案 1 :(得分:-1)
尝试:
List<List<Integer>> matrix = new ArrayList();
BufferedReader reader = null;
try {
reader = new BufferedReader(...);
String line = null;
while( ( line = reader.readLine() ) != null ) {
String[] tokens = line.split(",");
List<Integer> row = new ArrayList();
for (int i = 0; i < tokens.length; i++) {
row.add(Integer.parseInt(tokens[i]));
}
matrix.add(row);
}
} finally {
if (reader != null) {
reader.close();
}
}
我建议在文件的第一行包含文件和列的数量。类似的东西:
30,25
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
(...)
然后你可以读它并相应地创建一个int [] []多数组(从而提高内存使用率)。