我使用PushbackInputStream
来查看流中的下一个字节(bufferedIn
是BufferedInputStream
),因为我希望mark()
之前某个值,然后使用reset()
将之前倒回到它。
// Wrap input stream into a push back stream
PushbackInputStream pbBufferedIn = new PushbackInputStream(bufferedIn, 20);
boolean markDone = false; // Flag for mark
boolean resetDone = false; // Flag for reset
// Read each byte in the stream (some twice)
for (int i = pbBufferedIn.read(); i != -1; i = pbBufferedIn.read()) {
// Convert to byte
byte b = (byte) i;
// Check for marking before value -1
if (!markDone) {
if (b == -1) {
// Push character back
pbBufferedIn.unread(i);
// Mark for later rewind
pbBufferedIn.mark(20);
markDone = true;
System.out.print("[mark] ");
// Re-read
pbBufferedIn.read();
}
}
// Print the current byte
System.out.print(b + " ");
// Check for rewind after value 1
if (markDone && !resetDone && b == 1) {
pbBufferedIn.reset(); // <------ mark/reset not supported!
resetDone = true;
System.out.print("[reset] ");
}
}
具有讽刺意味的是PushbackInputStream
并不支持标记/重置...另一方面BufferedInputStream
支持标记/重置不具备推回机制......如何我可以吗?
答案 0 :(得分:1)
标记/重置等同于后推。 PushbackInputStream
适用于输入流不支持缓冲的情况。所以你读了,然后把它推回到流中。
使用BufferedInputStream
只需mark(10)
,使用read(10)
读取10个字节,然后调用reset()
。现在你的流回来了10个字节,你可以再次阅读它,所以你已经有效地选择了它。
答案 1 :(得分:1)
BufferedInputStream
(流重放):
PushbackInputStream
(流更正后的重放):
为简单起见,下面我提供相应的带有length-1缓冲区的示例:
PushbackInputStream pbis =
new PushbackInputStream(new ByteArrayInputStream(new byte[]{'a','b','c'}));
System.out.println((char)pbis.read());
System.out.println((char)pbis.read());
pbis.unread('x'); //pushback after read
System.out.println((char)pbis.read());
System.out.println((char)pbis.read());
BufferedInputStream bis =
new BufferedInputStream(new ByteArrayInputStream(new byte[]{'a','b','c'}));
System.out.println((char)bis.read());
bis.mark(1);//mark before read
System.out.println((char)bis.read());
bis.reset();//reset after read
System.out.println((char)bis.read());
System.out.println((char)bis.read());
结果:
a
b
x //correction
c
a
b
b //replay
c
答案 2 :(得分:0)
如果你有标记和重置,你也不需要回击。