java - PushbackInputStream 和标记/重置

标签 java stream reset push-back

我使用PushbackInputStream向前查看流中的下一个字节(bufferedIn,它是一个 BufferedInputStream),因为我想 mark() before 某个值,然后使用 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没有推回机制。 .我该怎么办?

最佳答案

BufferedInputStream(流重放):

  • 立即标记(开始创建缓冲区),以便您稍后可以重播(在某个缓冲区位置)。
  • 此外,您无法用其他内容替换缓冲的内容。

PushbackInputStream(流校正重放):

  • 始终有一个可用的缓冲区,您可以将其重置(在某个缓冲区位置)
  • 您可以向该缓冲区提供重播内容

为了简单起见,下面我提供了带有 length-1-buffers 的相应示例:

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

关于java - PushbackInputStream 和标记/重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848081/

相关文章:

java - android中解析xml属性

c# - 将图像作为二进制数据写入文本文件 C#

c++ - 从串行设备读取数据到数组 C++

javascript - 使用 jQuery 重置文本,存在 AJAX 调用

php - 寻找一些不错的选择来向用户发送重置密码电子邮件

java - 数据不会插入并显示在我的应用程序上 |安卓工作室

Java:为什么在 List 上调用 `remove()` 会抛出 UnsupportedOperation 异常?

Javascript 对象属性重置不起作用

java - 在android中比较两张脸

php - 带有超时的 SoapClient/Zend_Soap_Client