因此,在用 Java 制作 RPG 的过程中,我发现制作一个允许我创建 map 并保存 map 而无需编辑字节数组的数字的程序会很好。我需要能够将 map 保存到文本文件中,以便可以在 RPG 中读取和重新创建它。但是我不知道如何将 2D 字节数组写入文件。
例如:
byte[][] map = new byte[][]{ {0,0,0,0,0}, {1,1,1,0,0} };
我希望文本文件能够输出如下内容:
0 0 0 0 0
1 1 1 0 0
我到底该如何将二维字节数组的内容写入文本文件?
最佳答案
我认为最简单的方法:
// create your output stream. Use the current running directory for your project
FileOutputStream fout = new FileOutputStream(new File(System.getProperty("user.dir"), "test.txt"));
// print it out so you know where it is... maybe?
System.out.println(new File(System.getProperty("user.dir"), "test.txt"));
byte[][] map = new byte[][] { { 0, 0, 0, 0, 0 }, { 1, 1, 1, 0, 0 } };
// loop through your map, 2d style
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
// get the string value of your byte and print it out
fout.write(String.valueOf(map[i][j]).getBytes());
}
// write out a new line. For different systems the character changes
fout.write(System.getProperty("line.separator").getBytes());
}
// close the output stream
fout.close();
关于java - 将 2D 字节数组写入文本文件 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22756853/