2012-07-18 84 views
2

我想弄清楚如何到達使用java的二進制文件中的特定字節。我已經完成了大量關於字節級操作的閱讀,並且讓自己徹底感到困惑。現在我可以遍歷一個文件,如下面的代碼所示,並且告訴它停止在我想要的字節處。但是我知道這是一種無聊的行爲,而且有一種「正確」的方式來做到這一點。從二進制文件讀取特定字節

因此,例如,如果我有一個文件,我需要從偏移000400返回字節我怎麼能從FileInputStream得到這個?

public ByteLab() throws FileNotFoundException, IOException { 
     String s = "/Volumes/Staging/Imaging_Workflow/B.Needs_Metadata/M1126/M1126-0001.001"; 
     File file = new File(s); 
     FileInputStream in = new FileInputStream(file); 
     int read; 
     int count = 0; 
     while((read = in.read()) != -1){   
      System.out.println(Integer.toHexString(count) + ": " + Integer.toHexString(read) + "\t"); 
      count++; 
     } 
    } 

感謝

回答

10

需要RandomAccessFile作業。您可以通過seek()方法設置偏移量。

RandomAccessFile raf = new RandomAccessFile(file, "r"); 
raf.seek(400); // Goes to 400th byte. 
// ... 
2

您可以使用FileInputStream的skip()方法「跳過n個字節」。

雖然知道:

skip方法可以是,由於各種原因,最終超過 跳過的字節一些較小的數目,可能0

它返回實際字節數跳過,所以你應該喜歡的東西檢查:

long skipped = in.skip(byteOffset); 
if(skipped < byteOffset){ 
    // Error (not enough bytes skipped) 
}