Search code examples
javaioinputstreamoutputstream

Why does offset 0 when continuesly writing to OutputStream not result in dublicated Bytes?


I am downloading a File via http request and reading the InputStream to a byte[] and write that byte[]into a outputStream

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
int byteRead;         
buf = new byte[conn.getContentLength()];
while ((byteRead = is.read(buf)) != -1) {
       outStream.write(buf, 0, byteRead);
   } 

Let's say my byte[].length is 16. In the first while iteration the inputStream writes 4 Bytes [AAAA] into the byte[]. I now have a byte[] of 4 Bytes with a total byte[].length of 16. It would look like this: [AAAA ---- ---- ----]. Now i write that to the outputStream. The outputStream now contains [AAAA ---- ---- ----]

In the second iteration the inputStream writes another 4 Bytes [BBBB] into the byte[]. My byte[] now contains 8 Bytes: [AAAA BBBB ---- ----]. If I write that byte[] into my outputStream with an offset of 0 (the start of the byte[]) wouldn't that result in a doubling of the first 4 Bytes like this: [AAAA AAAA BBBB ----] ?


Solution

  • Your mistake is assuming that there is something keeping track of the offset inside the array, there is not.

    The InputStream / OutputStream often have an implicit offset (for example when they write to a file), but arrays does not.

    • your first read will leave your byte[] with the values [AAAA ---- ---- ----] (assuming it reads 4 bytes).
    • your second read will start from the beginning of the byte[] and leave it as [BBBB ---- ---- ----]

    This is even represented in your write call: the second argument tells the OutputStream at which index to start reading the byte[] and you always provide 0 (which is correct for this kind of loop).