【问题标题】:PushbackInputStream and mark/resetPushbackInputStream 和标记/重置
【发布时间】:2014-05-24 17:53:07
【问题描述】:

我使用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 没有推回机制...我该怎么办?

【问题讨论】:

    标签: java stream reset push-back


    【解决方案1】:

    BufferedInputStream(流回放):

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

    PushbackInputStream(流更正回放):

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

    为简单起见,下面我提供了带有长度为 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
    

    【讨论】:

    • 6年后,解决方案:) Tks.
    【解决方案2】:

    标记/重置有点相当于推回。 PushbackInputStream 适用于您的输入流不支持缓冲的情况。因此,您阅读,然后将其推回流中。

    使用BufferedInputStream 你只需mark(10),使用read(10) 读取这10 个字节,然后调用reset()。现在您的流返回了 10 个字节,您可以再次读取它,因此您已经有效地选择了它。

    【讨论】:

      【解决方案3】:

      如果你有标记和重置,你也不需要推回。

      【讨论】:

      • 我对你的解决方案很感兴趣,如果你有的话。
      猜你喜欢
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 2012-01-04
      • 2023-04-09
      • 2016-02-18
      • 1970-01-01
      • 2015-06-28
      相关资源
      最近更新 更多