2013-08-31 60 views
0

我有一個包含一些數據的文件。每個數據塊都有一個索引起始位置,所以我可以快速訪問它。根據程序啓動的方式(通過IDE或打開.jar文件),執行input.read()會得出不同的結果。必須使用skip()或read()取決於如何啓動應用程序

這是代碼塊使用:

注:這似乎只發生在一個文件中。

public static void main(String[] args) throws Exception 
{ 
    //The index is at position 137. 
    int indexPos = (Character.SIZE/8) * 137; 

    InputStream stream = InputStream stream = Test.class.getResourceAsStream("/data/data.dat"); 

    int response = JOptionPane.showConfirmDialog(null, "Use skip?"); 
    if (response == JOptionPane.YES_OPTION) 
    { 
     //Skips bytes to get to index position. 
     stream.skip(indexPos); 
    } 
    else 
    { 
     //Reads bytes to get to index position. 
     stream.read(new byte[indexPos]); 
    } 

    byte[] contentStart = new byte[2]; 
    stream.read(contentStart); 

    //The content itself start at this position. 
    int contentStartPos = ByteBuffer.wrap(contentStart).order(ByteOrder.BIG_ENDIAN).asCharBuffer().get(); 

    int response = JOptionPane.showConfirmDialog(null, "Use skip?"); 

    if (response == JOptionPane.YES_OPTION) 
    { 
     //Skips bytes to get to the correct position. 
     stream.skip(contentStartPos - indexPos - 2); 
    } 
    else 
    { 
     //Reads bytes to get to the correct position. 
     stream.read(new byte[contentStartPos - indexPos - 2]); 
    } 

    JOptionPane.showMessageDialog(null, "Should be 0 and is: "+stream.read()); 
} 

這裏是在最後被讀取字節的值:

//The correct value needed is 0. 
In IDE & yes yes: 108 
In IDE & no no: 0 
In IDE & yes no: 0 
In IDE & no yes: 112 
Via JAR & yes yes: 0 
Via JAR & no no: 4 
Via JAR and yes no: 4 
Via JAR and no yes: 0 

正如你所看到的,第一跳過/讀不要緊,它是什麼,以獲得正確的值。只有第二個。

我很想有人向我解釋爲什麼會發生這種情況。

編輯:這裏是被跳過的第二時間的值:

//The correct value is 8235. 
In IDE using skip: 8190 
In IDE using read: 8235 
Via JAR using skip: 8235 
Via JAR using read: 8192 
+0

我理解正確嗎?在所有組合中結果應爲0 – blackbird014

+0

@ blackbird014是的。我剛剛添加了正在讀取/跳過的字節數量。我明白,它可以警惕,但對於本地文件,我不知道它如何不能讀取請求的字節。以及爲什麼它根據應用程序的打開方式進行切換。 ((len = in.read(indexPos))!= -1);'對於read()並告訴我會發生什麼(如果現在結果是一致的?) –

+0

。關於skip():跳過並丟棄來自該輸入流的n個字節的數據。由於各種原因,跳過方法可能會跳過一些較小的字節數,可能爲0.這可能是由於許多條件中的任何一種導致的;在跳過n個字節之前達到文件結尾只是一種可能性。返回跳過的實際字節數。 Plz也打印字節,我們試圖瞭解那裏的行爲。 – blackbird014

回答

0

如果一個讀取的InputStream.skip)的Javadoc(方法:

跳過並丟棄n個字節的來自此輸入流的數據。由於各種原因,跳過方法可能會跳過一些較小的字節數,可能爲0.這可能是由於許多條件中的任何一種導致的;在跳過n個字節之前達到文件結尾只是一種可能性。返回跳過的實際字節數。

你需要把你的跳轉放在一個實際跳過字節的循環中。這是人們犯的一個常見錯誤,我知道我過去了。正如你所看到的,這個方法實際上會返回一個long值,你可以使用它來跟蹤跳過的實際字節數。

我希望這會有所幫助。

相關問題