本篇文章為大家展示了Android應(yīng)用中實(shí)現(xiàn)文件下載的方法有哪些,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

一、自己封裝URLConnection 連接請(qǐng)求類
public void downloadFile1() {
try{
//下載路徑,如果路徑無(wú)效了,可換成你的下載路徑
String url = "http://c.qijingonline.com/test.mkv";
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
final long startTime = System.currentTimeMillis();
Log.i("DOWNLOAD","startTime="+startTime);
//下載函數(shù)
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();//根據(jù)響應(yīng)獲取文件大小
if (fileSize <= 0) throw new RuntimeException("無(wú)法獲知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
File file1 = new File(path);
if(!file1.exists()){
file1.mkdirs();
}
//把數(shù)據(jù)存入路徑+文件名
FileOutputStream fos = new FileOutputStream(path+"/"+filename);
byte buf[] = new byte[1024];
int downLoadFileSize = 0;
do{
//循環(huán)讀取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
//更新進(jìn)度條
} 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);
}
}
當(dāng)前標(biāo)題:Android應(yīng)用中實(shí)現(xiàn)文件下載的方法有哪些-創(chuàng)新互聯(lián)
URL標(biāo)題:http://www.chinadenli.net/article28/dpoocp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)、App開發(fā)、品牌網(wǎng)站建設(shè)、企業(yè)建站、關(guān)鍵詞優(yōu)化、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容