Android应用中实现文件下载的方法有哪些-创新互联
本篇文章为大家展示了Android应用中实现文件下载的方法有哪些,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

一、自己封装URLConnection 连接请求类
public void downloadFile1() {
try{
//下载路径,如果路径无效了,可换成你的下载路径
String url = "http://c.qijingonline.com/test.mkv";
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
final long startTime = System.currentTimeMillis();
Log.i("DOWNLOAD","startTime="+startTime);
//下载函数
String filename=url.substring(url.lastIndexOf("/") + 1);
//获取文件名
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
int fileSize = conn.getContentLength();//根据响应获取文件大小
if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
File file1 = new File(path);
if(!file1.exists()){
file1.mkdirs();
}
//把数据存入路径+文件名
FileOutputStream fos = new FileOutputStream(path+"/"+filename);
byte buf[] = new byte[1024];
int downLoadFileSize = 0;
do{
//循环读取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
//更新进度条
} while (true);
Log.i("DOWNLOAD","download success");
Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));
is.close();
} catch (Exception ex) {
Log.e("DOWNLOAD", "error: " + ex.getMessage(), ex);
}
} 网页标题:Android应用中实现文件下载的方法有哪些-创新互联
文章分享:http://www.jxjierui.cn/article/dpoocp.html


咨询
建站咨询
