开发者

jump on specific location in binary file

I have a binary file which contains image.i have to jump on different locations in file to read the image file. So far i am usin开发者_如何转开发g mark and reset methods but these are not helping me as i want. please somebody help me about that i,ll be really thankful.and i am using Input Stream to read the file.


You can use the java.io.RandomAccessFile to do this. The methods seek(long) and getFilePointer() will help to jump to different offsets in the file and come back to original offsets:

RandomAccessFile f = new RandomAccessFile("/my/image/file", "rw");

// read some data.

long positionToJump = 10L;

long origPos = f.getFilePointer(); // store the original position

f.seek(positionToJump);
// now you are at position 10, start reading from here.

// go back to original position
f.seek(origPos);


Android seems to have RandomAccessFile, have you tried it?


Since Java 7 you can use java.nio.file.Files and SeekableByteChannel

byte[] getRandomAccessResults(Path filePath, long offset) throws IOException
{
    try (SeekableByteChannel byte_channel = java.nio.file.Files.newByteChannel(filePath, StandardOpenOption.READ))
    {
        ByteBuffer byte_buffer = ByteBuffer.allocate(128);
        byte_channel.position(offset);
        byte_channel.read(byte_buffer);
        return byte_buffer.array();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜