I have the following float array:
float[] arr = [ (1.2,2.3,2.4), (4.7,4.8,9.8) ]
and I wish to write it on a file through DataOutputStream
in bytes. I have tried this so far:
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]);
}
}
But I am getting this error:
The method writeByte(int) in the type DataOutputStream is not applicable for the arguments (float)
Normally, the same thing would work if arr
and integer array was. Does somebody know how I could write each element of the array as byte in the file? Thanks in advance
This code snippet is working:
// 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