I am writing to write out a 2-dimensional binary array in Java so that a legacy program written in C can read it. But if I use ObjectOutputStream's writeObject method it adds more bytes . What I mean is that output file contains more bytes than required. I guess I could write out the 2-dimensional array in C or C++ but before I do that wanted to know what the other possibilities are.
Asked
Active
Viewed 122 times
1
-
Why is this not a legitimate question ? – gansub Sep 29 '14 at 07:25
-
How does your C program read the data? What are the formatting requirements? – chrisb2244 Sep 29 '14 at 07:38
-
It needs to be read in as a 2-dimensional array of 16 bit unsigned integers. – gansub Sep 29 '14 at 07:45
-
+1 - decent question in my opinion. – David Victor Sep 29 '14 at 08:40
1 Answers
2
Starting with an array:
int rows = 6;
int columns = 5;
int i,j;
int[][] myArray = new int[rows][columns];
for (i=0; i<rows; i++) {
for (j=0; j<columns; j++) {
myArray[i][j] = i*j;
}
}
try {
FileOutputStream out = new FileOutputStream("outputDat");
ObjectOutputStream oout = new ObjectOutputStream(out);
for (i=0; i<rows; i++) {
for (j=0; j<columns; j++) {
oout.writeShort(myArray[i][j] & 0xFFFF); // Edited this line!
}
}
oout.close();
} catch (Exception ex) {
ex.printStackTrace();
}
This should output 2 byte (16-bit) integer values to your data file "outputDat". The order might need to be adjusted depending on how your values are arranged, since the format you specified in the comment link instructs starting from bottom-left.

chrisb2244
- 2,940
- 22
- 44
-
Beautiful. I was not aware of the writeShort method of ObjectOutpStream. – gansub Sep 29 '14 at 08:07
-
I need to write this out as unsigned 16 bit integers. So I added this line - shortVal =shortVal>=0?shortVal:0x10000+shortVal; But this wont compile. – gansub Sep 29 '14 at 08:27
-
Edited using http://stackoverflow.com/questions/6599548/convert-int-to-unsigned-short-java third answer. You can also use the `putChar()` method described in the accepted answer - depending on your setup in Java, that might be much easier/less messy – chrisb2244 Sep 29 '14 at 08:37