There are some codes in C++ like this:
struct Chunk
{
int flag;
int size;
};
Chunk chunk;
chunk.flag = 'DIVA';
chunk.size = 512;
Then write in to a file(fp is a pointer of file):
fwrite(&chunk, sizeof(chunk), 1, fp);
When in Java, to read the chunk, I need to do this
// Read file
byte[] fileBytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(fileBytes);
fis.close();
byte[] flag = new byte[4];
byte[] size = new byte[4];
//LITTLE_ENDIAN : reverse it
System.arraycopy(fileBytes, 0, flag, 0, flag.length);
System.arraycopy(fileBytes, flag.length, size, 0, size.length);
ArrayUtils.reverse(flag);
ArrayUtils.reverse(size);
Then, to check the result
if(Arrays.equals(flag, "DIVA".getBytes()))
{
// do sth.
}
Or do it this way in java('Bytes.toInt' is from HBase)
int flag;
int size;
flag = ByteBuffer.wrap(inBytes, startPos, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
size = ByteBuffer.wrap(inBytes, startPos + 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
Then do this to check this result
if(flag == Bytes.toInt("DIVA".getBytes()))
{
// do sth.
}
I hope I have expressed myself clearly. :)
My question is that two ways above, which is better ? Or is there a better way ?
What's more, Chunk is used as the head of a file.