我是 Java 新手,目前正在做一些实验。我写了一个小程序,它读取和写入 std I/O 流,但我不断收到超出范围的异常。这是我的代码
int BLOCKSIZE = 128*1024;
InputStream inStream = new BufferedInputStream(System.in);
OutputStream outStream = new BufferedOutputStream(System.out);
byte[] buffer = new byte[BLOCKSIZE];
int bytesRead = 0;
int writePos = 0;
int readPos = 0;
while ((bytesRead = inStream.read(buffer,readPos,BLOCKSIZE)) != -1) {
outStream.write(buffer,writePos,BLOCKSIZE);
readPos += bytesRead;
writePos += BLOCKSIZE;
buffer = new byte[BLOCKSIZE];
}
这是抛出的异常:“JavaPigz.main(JavaPigz.java:73) 处的 java.io.BufferedInputStream.read(BufferedInputStream.java:327) 线程“主”java.lang.IndexOutOfBoundsException 中的异常”
第 73 列是 inStream.read(...) 语句。基本上我想从标准输入读取 128kb 字节一次并将其写入标准输出并返回读取另一个 128kb 块,依此类推。同样的异常也会被抛出到 outStream.write()
我做了一些调试,它看起来 BufferedInputStream 缓冲区最多一次 64kb 块。不知道这是不是真的。谢谢你。
编辑:我也尝试过 InputStream inStream = new BufferedInputStream(System.in,BLOCKSIZE); 指定我想要的缓冲块的大小。但事实证明,无论指定什么,它都会保持 64kb 的大小