Search code examples
javajava-iobufferedinputstreamdatainputstream

Java BufferedInputStream.read() IndexOutOfBounds


i'm want to code a method that reads part from files into byte-arrays. for this i'm using fileinputstream and a buffered inputstream.

like this:

fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

I do this only once by calling a method name "OpenFile(String File)". Once the File has been opened with this method, i try to operate with the function: "ReadParts(byte[] buffer, int offset, int len)"

dis.read(buffer, offset, len);            
for(int i = 0; i < buffer.length; i++) System.out.print((char)buffer[i]);

// used data:
// file = "C:\Temp\test.txt" with a size of 949
// buffer: always in this case with a size of 237, except for the last one its 238
// offsets: 0, 237, 474, 711 
// len is always 237, except for the last one its 238

the line dis.read() throws after the first step always a indexOutOfBounds errormessage but i can't figure it out why and what. using the netbeans debugger didnt helped, since i can't find the problem with the indices.....


Solution

  • If you read the Stream into an array of buffers your offset and len will always have to be:

    offset = 0;
    len = buffer.length();
    

    These parameters specify where the data is put in the buffer and NOT which data is read from the Stream. The Stream is read continuus (or however this gets spelled?)!

    If you always call:

    buffer = new byte[256];
    dis.read(buffer, 0, 256);
    

    This will happen: Before the first call the Streamposition (position of the next byte that gets returned) is 0.

    1. Streamposition after call=256 and buffer contains the bytes 0-255
    2. Streamposition after call=512 and buffer contains the bytes 256-511
    3. ...

      dis.reset();

    Streamposition is 0 once more.

    This code reads only the bytes 256-511 from a Stream into a buffer:

    byte[] buffer = new byte[512];
    dis.skip(256);
    dis.read(buffer, 0, 256);
    

    See that the last 256 bytes of buffer aren't filled. This is one of the differences between read(byte[], int, int) and read(byte[])!

    Here are some links for you which describe the concept of a stream and the usage of read-method: read() Streams