java - 将 2D 字节数组写入文本文件 Java

标签 java arrays file-io io byte

因此,在用 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/

相关文章:

javascript - 从数组中删除指定值?

python - 沿一维的 1D 数组和 3D 数组的高效乘积 - NumPy

java - Java中使用数组反转数字

c - 如何获取包含文件的底层挂载 block 设备?

java - 如何删除 Java FX Accordion 默认边框?

java - 运行顺序作业 Hadoop

java - 返回 URI 给其他类

java - 如何获得数组中的多重模式?

java - 获取目录中文件的内容

c++ - 从文件中读取带空格的字符串