java正在读一个。将txt文件转换为二维数组列表
我正在用安卓创建一个游戏,游戏中的关卡将分别存储在不同的文件夹中。txt文件。每个级别都是一个字符网格,表示地图上的不同项目,但每个级别的大小不同,因此我想创建一段健壮的代码,用于读取文件,并将每个级别存储在2d arraylist中,无论其大小如何
我的第一次尝试:
private void loadLevel(String filename) {
mapWidth = 0;
mapHeight = 0;
BufferedReader br = null;
try {
String line = null;
br = new BufferedReader(new InputStreamReader(mContext.getAssets().open(filename)));
while ((line = br.readLine()) != null) {
mapArray.add(getLevelLine(line));
mapHeight++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private ArrayList<Character> getLevelLine(String line) {
ArrayList<Character> levelLine = new ArrayList<Character>();
if (line == null) return levelLine;
char[] lineArray = line.toCharArray();
for (char mapPiece : lineArray) {
levelLine.add(mapPiece);
}
mapWidth = lineArray.length;
return levelLine;
}
这有点低效,因为每行都会重新计算mapWidth,但它不起作用,因为读取了文本文件的第一条水平行,并将其存储在arraylist的第一个垂直列中,因此它会复制文本文件,但会交换x和y坐标
尝试2:
private void loadLevel(String filename) {
mapWidth = 0;
mapHeight = 0;
BufferedReader br = null;
try {
String line = null;
br = new BufferedReader(new InputStreamReader(mContext.getAssets().open(filename)));
while ((line = br.readLine()) != null) {
mapArray.add(new ArrayList<Character>());
char lineArray[] = line.toCharArray();
for (char mapPiece : lineArray) {
mapArray.get(mapHeight).add(mapPiece);
}
mapHeight++;
mapWidth = lineArray.length;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
这将以相同的方式计算贴图宽度,因此仍然有点效率低下。希望通过在arraylist中添加一个空条目,我可以循环遍历每个元素的第I个元素。第二次尝试也没有正确地增加mapHeight,因为在最后一次尝试中,mapHeight将增加,然后while循环将不会再次执行,但是出于某种原因,即使我在while循环之后从mapHeight中减去1,我也会得到一个索引越界错误。 更重要的是,通过手动设置mapWidth和mapHeight,我的第二次尝试似乎仍然在将x和y坐标存储到arraylist中时进行交换
我有什么明显的遗漏吗?似乎应该有一种相对简单的方法来实现这一点,不需要预先读取文本文件,并且避免使用普通的字符数组
提前感谢您的帮助
# 1 楼答案
我真的不明白为什么你们是第一个交换行和列的例子。 你没有说你在衡量你的表现。我的意思是什么对你更重要-速度还是内存消耗
无论如何,我写了一个示例输入。txt文件
a、b、c、d、e
f g h i g k
l m n o p q r
s t
u v
w
}
[a,b,c,d,e],[f,g,h,i,g,k],[l,m,n,o,p,q,r],[s,t],[u,v],[w]]
这是输出。这就是你想要的吗
我使用的是try with resources块,以防您不熟悉Java7的特性。遗憾的是,它在android上仍然不可用。真丢脸