【问题标题】:PushbackInputStream: Push back buffer is fullPushbackInputStream:推回缓冲区已满
【发布时间】:2013-10-15 03:58:52
【问题描述】:

为什么会出现以下异常:

Exception in thread "main" java.io.IOException: Push back buffer is full
    at java.io.PushbackInputStream.unread(PushbackInputStream.java:232)
    at java.io.PushbackInputStream.unread(PushbackInputStream.java:252)
    at org.tests.io.PushBackStream_FUN.read(PushBackStream_FUN.java:32)
    at org.tests.io.PushBackStream_FUN.main(PushBackStream_FUN.java:43)

在这段代码中:

public class PushBackStream_FUN {
    public int write(String outFile) throws Exception {
        FileOutputStream outputStream = new FileOutputStream(new File(outFile));
        String str = new String("Hello World");
        byte[] data = str.getBytes();
        outputStream.write(data);
        outputStream.close();

        return data.length;
    }

    public void read(String inFile, int ln) throws Exception {
        PushbackInputStream inputStream = new PushbackInputStream(new FileInputStream(new File(inFile)));
        byte[] data = new byte[ln];
        String str;

        // read
        inputStream.read(data);
        str = new String(data);
        System.out.println("MSG_0 = "+str);
        // unread
        inputStream.unread(data);
        // read
        inputStream.read(data);
        str = new String(data);
        System.out.println("MSG_1 = "+str);
    }

    public static void main(final String[] args) throws Exception {
        PushBackStream_FUN fun = new PushBackStream_FUN();
        String path = "aome/path/output_PushBack_FUN";
        int ln = fun.write(path);
        fun.read(path, ln);
    }
}

更新

认为这是解决方案。救援的 Java 资源。我做了一些“实验”。事实证明,当我使用指定的缓冲区大小指定 PushbackInputStream 时,它可以工作。 Java 源代码告诉我:

public PushbackInputStream(InputStream in) {
        this(in, 1);
    }

public PushbackInputStream(InputStream in, int size) {
        super(in);
        if (size <= 0) {
            throw new IllegalArgumentException("size <= 0");
        }
        this.buf = new byte[size];
        this.pos = size;
    }

我认为,如果您将PushbackInputStream 与使用默认缓冲区大小的构造函数一起使用,则只能读取单个字节。我未读的不止一个字节,因此例外。

【问题讨论】:

  • 你为什么要写这段代码?为什么你在阅读然后又阅读相同的东西?
  • 这只是一个示例,易于其他用户阅读和复制。 SSCCE

标签: java stream buffer ioexception pushbackinputstream


【解决方案1】:

默认情况下,PushbackInputStream 只为单个字符分配足够的空间以便unread()。如果您希望能够推回更多,则必须在构建时指定容量。

在你的情况下,它看起来像这样:

final PushbackInputStream pis = new PushbackInputStream( inputStream, ln );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2012-05-25
    • 2021-08-31
    • 2020-12-05
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多