I am using Java 1.5 on an embedded Linux device and want to read a binary file with 2 MB of int values. (now 4 bytes of Big Endian, but I can decide the format)
Using DataInputStreamthrough BufferedInputStreamwith dis.readInt()), these 500,000 calls take 17 seconds to read, but it takes 5 seconds to read a file into one large byte buffer.
How can I read this file faster in one huge int []?
The reading process should not use more than 512 kb.
This code below using niono faster than the readInt () method from java io.
int numInts = 500000;
int[] result = new int[numInts];
int cnt = 0;
RandomAccessFile aFile = new RandomAccessFile("filename", "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(512 * 1024);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
buf.flip();
while(buf.hasRemaining() && cnt < numInts){
result[cnt] = buf.getInt();
cnt++;
}
buf.clear();
bytesRead = inChannel.read(buf);
}
aFile.close();
inChannel.close();
Update: rating answers:
IntBuffer .
jit java.io DataiInputStream.readInt() (17s, 20s MemMap IntBuffer)
:
. ( init)