这是不检查可能发生的任何错误的情况非常乐观的实现。这只是一个使用字节数组而不是文件的例子。但它应该像使用文件输入和输出流替换字节数组流时一样工作。通过检查格式不正确的文件格式使其更加强大。
这个想法是在每行的前面加上它的长度,然后是行的字节。您的地图具有统一的列大小,因此您可以将每列的长度保存一次。只需按照自己的喜好调整即可。好玩:
public static void main(String[] args) throws Exception {
byte[][] dungeon = new byte[][] {
{0,0,0,0,0},
{1,1,1,0,0}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
saveMap(os, dungeon);
ByteArrayInputStream in = new ByteArrayInputStream(os.toByteArray());
byte[][] maze = loadMap(in);
}
private static void saveMap(OutputStream saveStream, byte[][] dungeon) throws Exception {
try (BufferedOutputStream os = new BufferedOutputStream(saveStream)) {
for (int row=0; row<dungeon.length; row++) {
os.write(toBytes(dungeon[row].length));
os.write(dungeon[row]);
}
}
}
private static byte[][] loadMap(InputStream saveStream) throws Exception {
List<byte[]> rows = new ArrayList<>();
try (BufferedInputStream in = new BufferedInputStream(saveStream)) {
while (in.available() != 0) {
byte[] column = new byte[toInt(in.read(), in.read())];
for (int idx = 0; idx < column.length; idx++) {
column[idx] = (byte) in.read();
}
rows.add(column);
}
}
return rows.toArray(new byte[rows.size()][]);
}
private static byte[] toBytes(int value) {
return new byte[] { (byte) (value >>> 8), (byte) value };
}
private static int toInt(int high, int low) {
return (high << 8) | (0x00FF & low);
}
谢谢!你的想法是最简单的,只需很少的调整! – user3140916