Java – the fastest way to read long [] from a file?
I have a file containing about 200000 long values, and I hope to read it into long [] It is suitable for Android applications; Function calls are slow (so anything involving reading a long time with a "for" loop will be super slow) I need to load to be fast What can I use? Everything I see seems to read only bytes quickly
I have used ByteBuffer and filechannel in NiO package before, which seems to be a fast way to load value array from file However, I can't figure out how to use it to read data into long [] I've tried to wrap long [] as a longbuffer, but I can't see any way to provide the data in the file to longbuffer
Edit: no matter what method I use, I need to be able to use arrays on the last long [] array binarySearch.
Solution
There is no way to convert byte [] to long [] However, you can try to use filechannel to read content into ByteBuffer, and then get longbuffer to ByteBuffer Aslongbuffer, from which you can get the length [] to longbuffer array().
You can also try using filechannel Map to get the mappedbytebuffer of the file This may be better than through filechannel Read is faster
If this does not work, you can try to use filechannel to read content into ByteBuffer, and then use ByteBuffer Getlong (index) accesses the long
Another solution (no method calls in loop: -)
byte[] byteArray = new byte[longCount * 8]; FileInputStream fis = new FileInputStream("lotsoflongs"); fis.read(byteArray); fis.close(); for (int i = 0; i < longCount; i += 8) longArray[i >> 3] = ((long) byteArray[0+i] << 56) + ((long)(byteArray[1+i] & 255) << 48) + ((long)(byteArray[2+i] & 255) << 40) + ((long)(byteArray[3+i] & 255) << 32) + ((long)(byteArray[4+i] & 255) << 24) + ((byteArray[5+i] & 255) << 16) + ((byteArray[6+i] & 255) << 8) + ((byteArray[7+i] & 255) << 0);
I have now benchmarked some solutions, and this solution seems to be the fastest way Also note that FIS The actual number of bytes read in read (bytearray) may be less than the actual size of bytearray Therefore, if this should be done correctly, you need to put it in the loop and iterate until all bytes are read