本篇文章為大家展示了Android應(yīng)用中實現(xiàn)文件下載的方法有哪些,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
一、自己封裝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); //下載函數(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("無法獲知文件大小 "); 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; //更新進度條 } 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)前標題:Android應(yīng)用中實現(xiàn)文件下載的方法有哪些-創(chuàng)新互聯(lián)
URL標題:http://jinyejixie.com/article28/dpoocp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護、App開發(fā)、品牌網(wǎng)站建設(shè)、企業(yè)建站、關(guān)鍵詞優(yōu)化、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)