跳转到二进制文件中的特定位置

我有一个二进制文件,其中包含image.i必须跳转到文件中的不同位置才能读取图像文件。 到目前为止,我正在使用标记和重置方法,但这些并没有像我想要的那样帮助我。 请有人帮助我,我会非常感谢。我正在使用输入流来读取文件。

您可以使用java.io.RandomAccessFile执行此操作。 方法seek(long)和getFilePointer()将有助于跳转到文件中的不同偏移量并返回到原始偏移量:

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似乎有RandomAccessFile ,你试过吗?

从Java 7开始,您可以使用java.nio.file.FilesSeekableByteChannel

 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(); } }