-1

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

hispanicprogrammer
  • 367
  • 3
  • 6
  • 22
  • 1
    In which version of Java this code compiles `float[] arr = [ (1.2,2.3,2.4), (4.7,4.8,9.8) ]`? – Nowhere Man Jun 19 '20 at 12:32
  • 1
    Please read the [docs](https://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html#writeFloat(float)). `DataOutputStream` has a `writeFloat` method – QBrute Jun 19 '20 at 12:33
  • @QBrute I want to store it as byte not as float – hispanicprogrammer Jun 19 '20 at 12:39
  • 1
    @hispanicprogrammer then what should `1.2` be represented as byte? A `float` in Java has a size of 4 bytes. Also have you read the linked documentation? `writeFloat` doesn't mean that there's a float value in your data. the "data" is always stored as bytes, so the method just takes the byte representation of your float and writes that to the stream. – QBrute Jun 19 '20 at 12:53

1 Answers1

1

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
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • Hey! I want to write every iteam of the array as byte not as float – hispanicprogrammer Jun 19 '20 at 12:40
  • Hey! `byte` is an integer type of 1 byte with range [-128, 127] and `float` has 4 bytes with its format. How do you want to press 4 bytes into 1? Of course, you may cast float to byte and lose all fraction part and limit the values with mentioned byte range. – Nowhere Man Jun 19 '20 at 12:43