我BufferedInputStream.read(字節[])的理解是,讀操作從POS開始,並讀取直到字節數組已滿或發生流的末尾。不一致的BufferedInputStream讀取(字節[])行爲
我呼籲在下面的BufferedInputStream readInt方法。
public class XDRInputStream {
private InputStream stream;
private byte[] buffer4 = new byte[4]; // fixed size buffers
private byte[] buffer8 = new byte[8];
public XDRInputStream(InputStream stream) {
this.stream = stream;
}
public InputStream getInternalStream() {
return stream;
}
public int readInt() throws IOException {
if (stream.read(buffer4) != -1) {
return ((buffer4[0] & 0xFF) << 24)
| ((buffer4[1] & 0xFF) << 16)
| ((buffer4[2] & 0xFF) << 8)
| ((buffer4[3] & 0xFF));
} else {
throw new EOFException("End of stream");
}
}
當我在Eclipse調試器跟蹤執行時,stream.read(buffer4)
呼叫 - 無論起始POS值的 - 通常會導致POS被設置爲4的值,和4個字節讀來自前四個字節輸入流。 read(byte [])調用是否在某些情況下靜默地重置流,如果是,何時?這似乎是有意的行爲(這不是我的代碼),當它以這種方式運行時,程序運行良好。
我遇到的問題是,有時候,只有在Windows上,並且只有當輸入流包含特定內容時(在這種情況下,由於丟棄的套接字導致的錯誤消息),pos的重置不會發生似乎意圖是,這會導致方法從流中的錯誤位置讀取並返回不正確的值。
我們在Solaris上使用相同的代碼,雖然我沒有做過這個平臺上調試器步進式,在Solaris下的程序工作正常,我試圖的bug修復不會發生。對於我不知道的流,是否會出現一些特定於平臺的問題?
謝謝。
您是否在到達「理解」之前閱讀Javadoc? – EJP 2012-07-10 09:58:08