Search code examples
javaarrayshttpurlinputstream

When downloading a file from a URL, why do we read into a byte array?


Why do we read into a byte array when downloading a file from a URL? In the below code a byte array ('data') is created which is allocated a number of "1024" and is passed as a parameter in the below piece of code

while ((x = in.read(data, 0, 1024)) >= 0)

Can you please explain what "reading" into a byte array means? Also, why were "0" and "1024" passed in as well?

This code was taken from Java getting download progress

URL url = new URL("http://downloads.sourceforge.net/project/bitcoin/Bitcoin/blockchain/bitcoin_blockchain_170000.zip");
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long completeFileSize = httpConnection.getContentLength();

java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(
        "package.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(
        fos, 1024);
byte[] data = new byte[1024];

long downloadedFileSize = 0;
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
    downloadedFileSize += x;

Solution

  • Can you please explain what "reading" into a byte array means?

    When we read data into a byte array, we mean that we store the data from an input stream into an array for later use. We read the data into a byte array instead of a char array or an int array because it is binary data. It might be text or a picture or a video. At the end of the day, these are all binary data that we store in bytes.

    Also, why were "0" and "1024" passed in as well?

    The documentation for read() says it takes 3 arguments:

    b - destination buffer.

    off - offset at which to start storing bytes.

    len - maximum number of bytes to read.

    So the 0 is the "offset" where the read operation will start storing bytes. The 1024 is the number of bytes to read. These can be any sensible numbers as long as you don't try to read into a location past the end of the array.