javabitstream

Save/Read matrix of integers in a binary file and read them


I want to know how can I save a matrix of integers to a binary file and read them back.

The matrix could be something like

double mat[][] = {{1, 0, 0, 0}, {1, 0, 1, 1}, {0, 1, 1, 0}};

I am able to save this in binary form but I am not sure how I am supposed to read them again and be able to tell each row apart (the matrix could have more than 4 columns I just randomly chose this one).

By the way would the resulting file be 16 bits in the case of the matrix above?


Solution

  • You could write your data into file as rows of characters '0' and '1' and split rows with line break (\n).

    But if you really want to save the data as individual bits to save space, then you won't be able to tell the dimensions of the matrix without explicitly specifying them in the file. You could write the dimensions as two first bytes in the file, then write your data as a flat stream of bits (for example, using java.util.BitSet.toByteArray()).