When reading from InputStream to ByteBuffer.array(), first 4 bytes of data are dropped

667 Views Asked by At

Let me give a simplified version of what I've tried. I have a file asset that contains a raw array of numbers (total of N number each is 4 bytes wide). I make an InputStream using AssetManager and try to push all the data into a direct ByteBuffer:

try (InputStream inputStream = assetsManager.open(assetFileName)) {
     int size = inputStream.available();
     assert size % 4 == 0;
     ByteBuffer bytes = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
     inputStream.read(bytes.array());
}

I thought that should work just fine, but I've met some strange behavior of my program that made me think that data loading was not correct after all, and indeed, after doing some debug logging of first content inside bytes and comparing it to the file content in a HEX viewer I found that this approach doesn't read the first 4 bytes, i.e. bytes content starts from my second 4 byte-wide number. I confess that I didn't check what's contained in the end of bytes, but let's assume it's just zeros.

I then resorted to another approach and it reads all the bytes fully and correctly (yet it's kind of ugly and I'd like to avoid it):

 try (InputStream inputStream = assetsManager.open(assetFileName) {
      int size = inputStream.available();
      byte[] bytesArray = new byte[size];
      inputStream.read(bytesArray, 0, size);
      ByteBuffer bytes = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
      bytes.put(bytesArray);
      bytes.rewind();
 }

I'm really a rookie of both Java and Android development, so I ask is this a platform-side bug, or is there something about InputStream / AssetManager.open(...) that I need to handle more carefully to achieve correct reading of data?

I've examined this question which sounds similar, but it's about C#: NetworkStream cuts off first 4 bytes when reading

It made me think that I should also read data in chunks and put them in ByteStream one by one, yet my files are not big (less than 16MB) and there's obviously no data race when reading, so I think inputStream.read(bytes.array()); shouldn't fail that strangely...

0

There are 0 best solutions below