jac
jac

Reputation: 71

reading buffered binary file (with seek)

Say I need to read huge binary file of integers, a handy way is:

FileInputStream fi = new FileInputStream(file);
BufferedInputStream bi = new BufferedInputStream( fi); 
DataInputStream di =new DataInputStream(bi);

But now say I have to read a huge block starting from the n-th integer. So far I have implemented a sort of buffer by myself as:

RandomAccessFile fp=new RandomAccessFile(file);
fp.seek(position);
byte[] buff= new  byte[len];
fp.read(buff, 0, len);
ByteArrayInputStream bIn = new ByteArrayInputStream(buff);
DataInputStream dIn= new DataInputStream(bIn);

now I can parse the data in buff, process it and then read the next block.

I was wondering if there was some standard buffer object I could have used. I would like to simplify my code and not to take care of the buffering by myself.

Any hint is welcome. Jacopo

Upvotes: 1

Views: 6327

Answers (2)

dspyz
dspyz

Reputation: 5510

Just start with fi.skip(position) before wrapping it with bi and di. The underlying stream actually makes a call to seek when position is sufficiently large.

Upvotes: 2

user207421
user207421

Reputation: 310913

Have a look at NIO. For example, java.nio.MappedByteBuffer.

Upvotes: 2

Related Questions