http://www.itivy.com/android/archive/2011/6/28/android-file-download.html
我们在开发中经常需要从服务器下载文件,下载的内容可能有交换的信息,缓存的图片,程序更新包等。我们使用URLConnection来实现下载。先看几行代码:
1
2
3
4
5
6
7
|
String urlDownload =
""
;
URL url =
new
URL(urlDownload );
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream
is
= con.getInputStream();
|
1
2
3
|
int
contentLength = con.getContentLength();
System.
out
.println(
"长度 :"
+contentLength)</SPAN>
|
我们常常会把文件下载到手机的存储卡里,所以还会用到获得存储卡路径的方法:
1
2
3
4
5
6
7
8
|
String dirName =
""
;
dirName = Environment.getExternalStorageDirectory()+
"/MyDownload/"
;
File f =
new
File(dirName);
if
(!f.exists())
{
f.mkdir();
}</SPAN>
|
做完了上面的准备后,基本就能实现下载了。我们看看主要的完整代码。
下载前的准备工作:
1
2
3
4
5
6
7
8
9
10
11
12
|
//要下载的文件路径
String urlDownload =
""
;
//urlDownload = "http://192.168.3.39/text.txt%22;
urlDownload = "http:
//www.baidu.com/img/baidu_sylogo1.gif%22;
// 获得存储卡路径,构成 保存文件的目标路径
String dirName =
""
;
dirName = Environment.getExternalStorageDirectory()+
"/MyDownload/"
;
File f =
new
File(dirName);
if
(!f.exists())
{
f.mkdir();
}
|
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
|
//准备拼接新的文件名(保存在存储卡后的文件名)
String newFilename = _urlStr.substring(_urlStr.lastIndexOf(
"/"
)+1);
newFilename = _dirName + newFilename;
File file =
new
File(newFilename);
//如果目标文件已经存在,则删除。产生覆盖旧文件的效果
if
(file.exists())
{
file.delete();
}
try
{
// 构造URL
URL url =
new
URL(_urlStr);
// 打开连接
URLConnection con = url.openConnection();
//获得文件的长度
int
contentLength = con.getContentLength();
System.
out
.println(
"长度 :"
+contentLength);
// 输入流
InputStream
is
= con.getInputStream();
// 1K的数据缓冲
byte
[] bs =
new
byte
[1024];
// 读取到的数据长度
int
len;
// 输出的文件流
OutputStream os =
new
FileOutputStream(newFilename);
// 开始读取
while
((len =
is
.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is
.close();
}
catch
(Exception e) {
e.printStackTrace();
}
|