生活随笔
收集整理的這篇文章主要介紹了
Android根据URL下载文件保存到SD卡
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?//下載具體操作??????private?void?download()?{??????????try?{??????????????URL?url?=?new?URL(downloadUrl);??????????????//打開連接??????????????URLConnection?conn?=?url.openConnection();??????????????//打開輸入流??????????????InputStream?is?=?conn.getInputStream();??????????????//獲得長度??????????????int?contentLength?=?conn.getContentLength();??????????????Log.e(TAG,?"contentLength?=?"?+?contentLength);??????????????//創(chuàng)建文件夾?MyDownLoad,在存儲卡下??????????????String?dirName?=?Environment.getExternalStorageDirectory()?+?"/MyDownLoad/";??????????????File?file?=?new?File(dirName);??????????????//不存在創(chuàng)建??????????????if?(!file.exists())?{??????????????????file.mkdir();??????????????}??????????????//下載后的文件名??????????????String?fileName?=?dirName?+?"xiaomibianqian.apk";??????????????File?file1?=?new?File(fileName);??????????????if?(file1.exists())?{??????????????????file1.delete();??????????????}??????????????//創(chuàng)建字節(jié)流??????????????byte[]?bs?=?new?byte[1024];??????????????int?len;??????????????OutputStream?os?=?new?FileOutputStream(fileName);??????????????//寫數(shù)據(jù)??????????????while?((len?=?is.read(bs))?!=?-1)?{??????????????????os.write(bs,?0,?len);??????????????}??????????????//完成后關(guān)閉流??????????????Log.e(TAG,?"download-finish");??????????????os.close();??????????????is.close();??????????}?catch?(Exception?e)?{??????????????e.printStackTrace();??????????}??????}??}??? ? String?dirName?=?Environment.getExternalStorageDirectory()?+?"/MyDownLoad/";?? <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
轉(zhuǎn)載于:https://www.cnblogs.com/wcLT/p/8513955.html
總結(jié)
以上是生活随笔為你收集整理的Android根据URL下载文件保存到SD卡的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。