Android中如何实现文件下载
来源:互联网 发布:js字符串相加 编辑:程序博客网 时间:2024/05/16 15:46
http://www.itivy.com/android/archive/2011/6/28/android-file-download.html
我们在开发中经常需要从服务器下载文件,下载的内容可能有交换的信息,缓存的图片,程序更新包等。我们使用URLConnection来实现下载。先看几行代码:
1
2
3
4
5
6
7
String urlDownload =
""
;
urlDownload =
"http://www.baidu.com/img/baidu_sylogo1.gif"
;
URL url =
new
URL(urlDownload );
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream
is
= con.getInputStream();
1
2
3
<SPAN xmlns=
"http://www.w3.org/1999/xhtml"
>//获得文件的长度
int
contentLength = con.getContentLength();
System.
out
.println(
"长度 :"
+contentLength)</SPAN>
我们常常会把文件下载到手机的存储卡里,所以还会用到获得存储卡路径的方法:
1
2
3
4
5
6
7
8
<SPAN xmlns=
"http://www.w3.org/1999/xhtml"
>// 获得存储卡路径,构成 保存文件的目标路径
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();
}
- Android中如何实现文件下载
- Android中如何实现文件下载
- Android中如何实现文件下载
- Android中如何实现文件下载
- Android中如何实现文件下载
- Android中实现文件下载
- 如何在.net中实现文件下载
- Android 中 DownLoadManager 实现文件下载
- Android 中 DownLoadManager 实现文件下载
- 如何实现文件下载
- 如何实现下载文件
- android中如何下载文件并显示下载进度
- android中如何下载文件并显示下载进度
- Android中如何利用xUtils简单快捷的实现文件下载
- Android实现文件下载
- android 实现文件下载
- android实现文件下载
- WEB项目中如何实现禁止下载文件(一)
- UVa 116 - Unidirectional TSP
- Java六种异常处理的陋习(转载)
- RAM、ROM、Flash
- centos + qmail 在本机能telnet 到smtp 外网不能
- ubuntu下gcc的安装与使用
- Android中如何实现文件下载
- Windows 使用pip安装 Django
- ubuntu 安装初配 双网卡 网络配置
- linux 下载文件
- ubuntu 安装qmail配合的 deamontools时添加自动启动失效
- linux ./命令 形式运行命令
- oauth在客户机请求授权时检测二者时间差
- linux vi 删除指定所有字符
- smtp发件测试