Java PushbackInputStream:PushBack缓冲区已满
为什么我会遇到以下异常:Java PushbackInputStream:PushBack缓冲区已满,java,stream,buffer,ioexception,pushbackinputstream,Java,Stream,Buffer,Ioexception,Pushbackinputstream,为什么我会遇到以下异常: 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.
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;
}
public PushbackInputStream(InputStream-in){
这(在,1);
}
公共PushbackInputStream(输入流输入,整数大小){
超级(in),;
如果(size默认情况下,PushbackInputStream
仅为单个字符分配足够的空间unread()
。如果希望能够向后推得更多,则必须在构建时指定容量
在你的情况下,它看起来像这样:
final PushbackInputStream pis = new PushbackInputStream( inputStream, ln );
你为什么要写这段代码?你为什么要读一遍又一遍同样的东西?这只是一个例子,其他用户很容易阅读和复制。SSCCE