如何将二维浮点数组作为字节写入文件中?

How to write a 2D array of floats in a file as bytes?

我有以下浮点数组:

float[] arr = [ (1.2,2.3,2.4), (4.7,4.8,9.8) ]

我希望通过 DataOutputStream 以字节为单位将其写入文件。到目前为止我已经试过了:

      DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));

      for(int row = 0; row<arr.length; row ++) {
                for(int column = 0; column<arr[0].length; column++) {
                    out.writeByte(arr[row][column]);
                }
            }

但是我收到这个错误:

The method writeByte(int) in the type DataOutputStream is not applicable for the arguments (float)

通常,如果 arr 和整数数组是,同样的事情会起作用。有人知道我如何将数组的每个元素写为文件中的字节吗?提前致谢

此代码片段有效:

// fix array declaration
float[][] arr = { {1.2f,2.3f,2.4f}, {4.7f,4.8f,9.8f} };

// use try-with-resources to close output stream automatically
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("floats.dat"))) {
    for (int row = 0; row < arr.length; row++) {
        for (int column = 0; column < arr[row].length; column++) {
            out.writeFloat(arr[row][column]);
        }
    }
}
// resulting file has length 24 bytes

try (DataOutputStream out = new DataOutputStream(new FileOutputStream("float_bytes.dat"))) {
    for (int row = 0; row < arr.length; row++) {
        for (int column = 0; column < arr[row].length; column++) {
            out.writeByte((byte)arr[row][column]);
        }
    }
}
// resulting file has length 6 bytes