咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

Android 简单文件下载

Android 上有很多优秀的第三方下载库,功能很强大,如断点续传,异步等。

为了快速下载一个小文件,有时候并不需要牛刀,利用Android自带的 java.net.HttpURLConnection 即可以完成下载,应用场景,比如小的缓存文件,用子线程同步下载即可。

步骤(经典的阻塞输入/输出流读写):

  1. 连接
  2. 获取输入流
  3. 读取buffer写入到本地文件输出流
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MiniFileDownload {

private static final String TAG = "MiniFileDownload";
interface DownloadCallBack{
void onError(Exception e);
void onOK(File file);
void onProgress(float progress);
}
public static void start(String url, File saveFile, DownloadCallBack callBack) {

if(saveFile.exists()){
saveFile.delete();
}
if(callBack == null){
return;
}
HttpURLConnection conn;
try {

//连接URL服务器
conn = (HttpURLConnection)new URL(url).openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setUseCaches(false);
} catch (IOException e) {
e.printStackTrace();
callBack.onError(e);
return;
}

InputStream is = null;
BufferedOutputStream bos = null;
try {

//判断响应码,如果服务器不响应错误,开始下载。
if (conn.getResponseCode() != 200){
Log.e(TAG,"ResponseCode = " + conn.getResponseCode());
return;
}
//获取文件总大小
int contentLength = conn.getContentLength();
Log.d(TAG,"content Length = " + contentLength);
byte[] buffer = new byte[1024];
int offset = 0 ;
int len;

//本地文件输出流
bos = new BufferedOutputStream( new FileOutputStream(saveFile) );

//获取输入流
is = conn.getInputStream();
//循环读(下载)
while ((len = is.read(buffer)) != -1) {

Log.d(TAG,"read buffer len = " + len);
bos.write(buffer, 0, len);
offset += len;
Log.d(TAG,"offset = " + offset + " ;total=" + contentLength);
//计算进度
float progress = (float)offset / (float)contentLength;
Log.d(TAG,"progress = " + progress);
//更新进度到回调,UI层可以显示下载进度
callBack.onProgress(progress);
}
Log.d(TAG,"ok");
callBack.onOK(saveFile);
} catch (IOException e) {
e.printStackTrace();
callBack.onError(e);
}finally {

//关闭资源
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if(bos != null){
try {
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
conn.disconnect();
}
}

}