gansub
gansub

Reputation: 1174

Java ByteBuffer for Zipfile

I have a binary file that contains big endian data. I am using this code to read it in

FileChannel fileInputChannel = new FileInputStream(fileInput).getChannel();
ByteBuffer bb  = ByteBuffer.allocateDirect((int)fileInputChannel.size());
while (bb.remaining() > 0)
    fileInputChannel.read(bb);
fileInputChannel.close();
bb.flip();

I have to do something identical for zip files. In other words decompress the file from a zip file and order it. I understand I can read it in via ZipInputStream but then I have to provide the coding for the "endianness". With ByteBuffer you can use ByteOrder.

Is there an NIO alternative for zip files ?

Upvotes: 1

Views: 2350

Answers (1)

Holger
Holger

Reputation: 298103

If you have your ZipInputStream, just use Channels.newChannel to convert it to a Channel then proceed as you wish. But you should keep in mind that it might be possible that a ZipInputStream can’t predict its uncompressed size so you might have to guess the appropriate buffer size and possibly re-allocate a bigger buffer when needed. And, since the underlying API uses byte arrays, there is no benefit in using direct ByteBuffers in the case of ZipInputStream, i.e. I recommend using ByteBuffer.allocate instead of ByteBuffer.allocateDirect for this use case.

By the way you can replace while(bb.remaining() > 0) with while(bb.hasRemaining()). And since Java 7 you can use FileChannel.open to open a FileChannel without the detour via FileInputStream.

Upvotes: 3

Related Questions