reading buffered binary file (with seek)

时光怂恿深爱的人放手 提交于 2019-11-29 23:49:01

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4375118/reading-buffered-binary-file-with-seek

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!