Benas
Benas

Reputation: 2332

Java. How to get constant read times from text file?

I have text file which contains over 1kk integer numbers. I want to read the n-th number in constant time. I'm not allowed to put all integers in the array. I heard that there is a technique which operates with bytes, so I could just write method "getNthInteger(int nth, int elementLengthInBytes)" or something like that. Please give me reference to this technique, any help is appreciated!

Upvotes: 0

Views: 331

Answers (1)

Jay
Jay

Reputation: 9582

You convert each integer to an array of bytes of some length L, then write the bytes to the file. L must be exactly the same for each integer. Then to read integer N, read L bytes starting from byte N*L.


For example:

You can write an integer to a file as 4 bytes with java.io.RandomAccessFile.writeInt(int).

You can read the Nth integer with:

java.io.RandomAccessFile.seek(n*4);
int i = java.io.RandomAccessFile.readInt();

Replace java.io.RandomAccessFile with an actual object of type java.io.RandomAccessFile.

Upvotes: 2

Related Questions