Reputation: 327
I'm new to Java and currently doing some experiments on it. I wrote a little program that does read and write stream of std I/O but I kept getting exceptions thrown for out of range. Here is my code
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];
}
Here is the exception thrown:"Exception in thread "main" java.lang.IndexOutOfBoundsException at java.io.BufferedInputStream.read(BufferedInputStream.java:327) at JavaPigz.main(JavaPigz.java:73)"
73th col is the inStream.read(...) statement. Basically I want to read 128kb bytes from stdin once and write it to the stdout and go back to read another 128kb chunk, so on and so forth. The same exception is also thrown to outStream.write()
I did some debugging and it looks BufferedInputStream buffers at most 64kb chunk once. Don't know if this is true. Thank you.
Edit: I also tried doing InputStream inStream = new BufferedInputStream(System.in,BLOCKSIZE); to specify the size of buffered chunk I want. But turns out it keeps giving size of 64kb no matter what is specified
Upvotes: 1
Views: 8501
Reputation: 76898
You're increasing your readPos
(and writePos
) in your loop. The subsequent reads are starting at that offset for inserting into your buffer
, and attempting to write BLOCKSIZE
bytes into it ... which won't fit, thus giving you an index out of bounds error.
The way you have that loop written, readPos
and writePos
should always be 0
especially since you're creating a new buffer every time. That being said ... you really don't want to do that, you want to re-use the buffer. It looks like you're just trying to read from the input stream and write it to the output stream ...
while ((bytesRead = inStream.read(buffer,readPos,BLOCKSIZE)) != -1) {
outStream.write(buffer,writePos,bytesRead);
}
Upvotes: 3
Reputation: 10257
your readPos and writePos correspond to the array ... not to the stream ...
set them 0 and leave them at 0
in your write call set param 3 to bytesRead instead of BLOCKSIZE
Upvotes: 0