blob: 806f17351872fd13da45e8a1db1a86cca230bdd6 [file] [log] [blame]
Zhomart Mukhamejanov93535dd2018-04-26 16:10:12 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.example.android.systemupdatersample.util;
18
19import android.util.Log;
20
21import java.io.File;
22import java.io.FileOutputStream;
23import java.io.IOException;
24import java.io.InputStream;
25import java.io.OutputStream;
26import java.net.URL;
27import java.net.URLConnection;
28
29/**
30 * Downloads chunk of a file from given url using {@code offset} and {@code size},
31 * and saves to a given location.
32 *
33 * In real-life application this helper class should download from HTTP Server,
34 * but in this sample app it will only download from a local file.
35 */
36public final class FileDownloader {
37
38 private String mUrl;
39 private long mOffset;
40 private long mSize;
41 private File mOut;
42
43 public FileDownloader(String url, long offset, long size, File out) {
44 this.mUrl = url;
45 this.mOffset = offset;
46 this.mSize = size;
47 this.mOut = out;
48 }
49
50 /**
51 * Downloads the file with given offset and size.
52 */
53 public void download() throws IOException {
54 Log.d("FileDownloader", "downloading " + mOut.getName()
55 + " from " + mUrl
56 + " to " + mOut.getAbsolutePath());
57
58 URL url = new URL(mUrl);
59 URLConnection connection = url.openConnection();
60 connection.connect();
61
62 // download the file
63 try (InputStream input = connection.getInputStream()) {
64 try (OutputStream output = new FileOutputStream(mOut)) {
65 long skipped = input.skip(mOffset);
66 if (skipped != mOffset) {
67 throw new IOException("Can't download file "
68 + mUrl
69 + " with given offset "
70 + mOffset);
71 }
72 byte[] data = new byte[4096];
73 long total = 0;
74 while (total < mSize) {
75 int needToRead = (int) Math.min(4096, mSize - total);
76 int count = input.read(data, 0, needToRead);
77 if (count <= 0) {
78 break;
79 }
80 output.write(data, 0, count);
81 total += count;
82 }
83 if (total != mSize) {
84 throw new IOException("Can't download file "
85 + mUrl
86 + " with given size "
87 + mSize);
88 }
89 }
90 }
91 }
92
93}