2010-09-02 55 views
2

我有一個包含image.i的二進制文件,它必須在文件中的不同位置上跳轉以讀取圖像文件。到目前爲止,我正在使用標記和重置方法,但這些並沒有幫助我,因爲我想。 請有人幫我介紹一下,我會非常感謝。而且我使用輸入流來讀取文件。在二進制文件中的特定位置跳轉

+0

你可以刪除部分代碼爲你的第一句話?這樣,你的問題會更容易閱讀。 – 2010-09-02 06:46:44

回答

4

您可以使用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); 
2

Android似乎有RandomAccessFile,你試過了嗎?

+0

我可以在輸入流中使用它嗎? – sajjoo 2010-09-02 06:49:55

+0

如果你已經有FileInputStream(不是通用的InputStream!),你可以使用getChannel()方法來獲得FileChannel。但是打開新的RandomAccessFile更簡單。 – 2010-09-02 06:51:45

+0

@sajjoo - ['FileInputStream'](http://download-llnw.oracle.com/javase/6/docs/api/index.html?java/lang/String.html)提供了一個'getChannel()'方法。 – 2010-09-02 07:03:25

0

由於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(); 
    } 
} 
相關問題