I have a file that contains about 200,000 long values that I want to read as fast as possible into a long[]. It’s for an Android app; function calls are slow (so anything involving reading a long at a time with a “for” loop will be super slow) and I need loading to be fast. What can I use? Everything I look at seems to read only bytes fast.
I’ve used ByteBuffer and FileChannel from the NIO package before and this seems a really fast way to load arrays of values from files. However, I cannot work out how to use this to read data into a long[]. I’ve tried wrapping a long[] as a LongBuffer, but I cannot see any way I can feed data from a file into a LongBuffer.
Edit: Whatever method I use, I need to be able to use Arrays.binarySearch on the long[] array at the end.
There is no way to cast a
byte[]into along[]. However, you could try to use aFileChannelto read the content into aByteBufferand then get hold of aLongBufferthroughByteBuffer.asLongBufferfrom which you could get along[]throughLongBuffer.array().You could also try
FileChannel.mapto get aMappedByteBufferof the file. This may be faster than going through aFileChannel.read.If this doesn’t work you could try to use a
FileChannelto read the content into aByteBufferand then access thelongs inside it, usingByteBuffer.getLong(index).An alternative solution. (No method-calls in the loop 🙂
I’ve benchmarked a few solutions now, and this one seems to be the fastest way of doing it. Also, note that the actual bytes read in
fis.read(byteArray)may be less than the actual size of byteArray. Thus, if this should be done properly, you need to put it in a loop that iterates until all bytes have been read.