user2718995
user2718995

Reputation: 21

Android Partially Downloaded Files Report Wrong File Size

I'm putting together some code to download files from an HTTP address in Android. I'd like to support download resumption if the download fails mid way.

The output I get when starting the download, then killing the wifi connection and restarting again several times is the following:

Start size 0 Stop size 12333416 Start size 12333416 Stop size 16058200 Start size 3724784

I cannot understand why after the first resumption, subsequent file size readings of the partially downloaded file do not match.

Thanks in advance!

public void download(String source, String target) throws IOException {
    BufferedOutputStream outputStream = null;
    InputStream inputStream = null;

    try {
        File targetFile = new File(target);
        currentBytes = targetFile.length();

        Log.i(TAG, "Start size " + String.valueOf(currentBytes));
        outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));

        // create the input stream
        URLConnection connection = (new URL(source)).openConnection();
        connection.setConnectTimeout(mCoTimeout);
        connection.setReadTimeout(mSoTimeout);

        inputStream = connection.getInputStream();
        inputStream.skip(currentBytes);

        // calculate the total bytes
        totalBytes = connection.getContentLength();

        byte[] buffer = new byte[1024];
        int bytesRead;

        while ((bytesRead = inputStream.read(buffer)) > 0) {
            // write the bytes to file
            outputStream.write(buffer, 0, bytesRead);
            outputStream.flush();

            currentBytes += bytesRead;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            // close the output stream
            outputStream.flush();
            outputStream.close();
        }

        if (inputStream != null) {
            // close the input stream
            inputStream.close();
        }

        Log.i(TAG, "Stop size " + String.valueOf(currentBytes));
    }
}

Upvotes: 2

Views: 723

Answers (1)

grapescan
grapescan

Reputation: 251

There are two things you are doing wrong:

  1. To resume download to file you should append, not rewrite the file. Use special constructor for output stream:

    FileOutputStream(targetFile, true)

  2. To request part of file from server you should use HTTP 1.1 property "Range". You can do it like this:

    HttpURLConnection httpConnection = (HttpURLConnection) connection; connection.setRequestProperty("Range", "bytes=" + currentBytes + "-");

Upvotes: 1

Related Questions