alessandro
alessandro

Reputation: 1721

Java - IntBuffer wrapping

I am reading a integer file using :

int len = (int)(new File(file).length());
FileInputStream fis = new FileInputStream(file);
byte buf[] = new byte[len];
fis.read(buf);
IntBuffer up = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();

But, it creates two copies of file in memory, 1) Byte Array copy 2) IntBuffer copy.

Is it possible to use the code in such a way thus it will create only one copy in memory?

Upvotes: 7

Views: 2716

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533750

I suggest you compare this with

FileChannel fc = new FileInputStream(file).getChannel();
IntBuffer ib = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size())
        .order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();

This uses less than 1 KB of heap regardless of the file size.

BTW: This can be much faster than using a heap buffer because it doesn't need to assemble each int value from bytes.

Upvotes: 2

Tim Bender
Tim Bender

Reputation: 20442

The javadocs and the implementation from Oracle that I've looked at indicate that what you are saying is not true. The javadocs say that:

public static ByteBuffer wrap(byte[] array)

Wraps a byte array into a buffer.

The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa.

The code shows that the array passed into ByteBuffer.wrap is simply assigned as the internal array of the ByteBuffer. The ByteBuffer.asIntBuffer method simply shows the creation of an IntBuffer that uses the ByteBuffer.

Upvotes: 6

Related Questions