I am a C++ programmer, working on a java program. I need to read a
binary file using Java.
Here is how I read it in C++,
Struct SOME_DATA
{
unsigned long data1;
unsigned short data2;
unsigned short data3;
unsigned long data4;
}
struct SOME_DATA someData;
and read using
fread(&someData, 12, 1, inputFile);
This is already a stupid idea in C++, since there is no guarantee that
sizeof(SOME_DATA) == 12. Since this is a Java group I'd like to
recommend that you consult some C++ resource regarding struct
alignment and padding, data type size, and (network) byte order.
In Java (assuming you have fixed you C++ problem), one would read this
e.g. with a DataInputStream:
/*
* Read data using network byte-order, aka big-endian
* byte-order (MSB first), and no padding/alignment
* between the data.
*/
class Data {
/*
* Note, Java has no unsigned data types.
* Therefore in this example I store the unsigned short
* in a (signed) int, and the unsigned long in a BigInteger
* Typically, in a carefully designed application this
* can be avoided, but I do it here to avoid discussion
* of using signed data types to handle unsigned types.
*/
private BigInteger data1; // data format: unsigned long64
private int data2; // data format: unsigned short16
private int data3; // data format: unsigned short16
private BigInteger data4; // data format: unsigned long64
public void read(DataInputStream in) throws IOException {
byte ulong2big[] = new byte[5];
ulong2big[0] = 0; // ensure MSB is always zero, so
// we get an unsigned interpretation
// of the following 4 byte data
// when converting the array to a
// BigInteger
// Read four bytes and convert them to a BigInteger
// In carefully designed applications a
// data1 = in.readLong() would do.
in.read(ulong2big, 1, 4); // TODO: check return value
data1 = new BigInteger(ulong2big);
// Read the unsigned short into an int
data2 = in.readUnisgnedShort();
// in.skipByte(...) in case padding needs to be skipped
data3 = in.readUnsignedShort();
// in.skipByte(...) in case padding needs to be skipped
// Read four bytes and convert them to a BigInteger
// In carefully designed applications a
// data4 = in.readLong() would do.
in.read(ulong2big, 1, 4); // TODO: check return value
data4 = new BigInteger(ulong2big);
}
}