Q:

Having an issue writing to DataOutputStream and reading from RandomAccessFile with a buffer

    DataOutputStream lWriter = new DataOutputStream(connection.getOutputStream());

    int bytesRead = 0;
    int offset = 0;
    byte[] bytes = new byte[1048576]; // read 1MB at a time
    RandomAccessFile f = new RandomAccessFile(xmlFile, "rw");
    while(bytesRead != -1){
        offset += f.read(bytes, offset, bytes.length);
        if (bytesRead != -1){
             lWriter.write(bytes, 0, bytes.length);
        }
}

With this code I'm getting an index out of bounds exception at f.read(). I'm probably misusing the arguments offset and length incorrectly. Wouldn't each time I read in a chunk, I should move the offset the size of the chunk? Maybe I just need to read less in at time and use a smaller buffer?
Currently I have this implementation working, but I'm worried about memory usage:
DataOutputStream lWriter = new DataOutputStream(connection.getOutputStream());      
lWriter.write(fileToBytes(xmlFile));

Thanks for any help!

A:

The canonical way to copy streams in Java is as follows:
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
    // bytesRead += count; // if you are counting
}

Your loop contains numerous errors. The offset is the offset into the buffer, not the file, and you rarely have to use it at all. You don't have to advance the offset. You are testing bytesRead but never setting it after initialisation. You aren't checking for EOS before advancing the count.  You aren't using the read count when writing, so you're writing junk to the file.

