1

我是 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 的大小

4

2 回答 2

3

你正在增加你的readPos(and writePos) 在你的循环中。随后的读取从插入到您的偏移量开始buffer,并尝试将BLOCKSIZE字节写入其中......这不适合,从而给您一个索引越界错误。

您编写该循环的方式,readPos并且writePos应该始终如此,0因为您每次都在创建一个新缓冲区。话虽这么说......你真的不想这样做,你想重新使用缓冲区。看起来您只是想从输入流中读取并将其写入输出流......

while ((bytesRead = inStream.read(buffer,readPos,BLOCKSIZE)) != -1) {
    outStream.write(buffer,writePos,bytesRead);
}
于 2012-02-07T06:10:04.977 回答
0

您的 readPos 和 writePos 对应于数组...而不是流...

将它们设置为 0 并将它们保留为 0

在您的写调用中将参数 3 设置为 bytesRead 而不是 BLOCKSIZE

于 2012-02-07T06:12:29.740 回答