Android根據URL下載文件保存到SD卡


  •  //下載具體操作  
  •     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);  
  •             //創建文件夾 MyDownLoad,在存儲卡下  
  •             String dirName = Environment.getExternalStorageDirectory() + "/MyDownLoad/";  
  •             File file = new File(dirName);  
  •             //不存在創建  
  •             if (!file.exists()) {  
  •                 file.mkdir();  
  •             }  
  •             //下載后的文件名  
  •             String fileName = dirName + "xiaomibianqian.apk";  
  •             File file1 = new File(fileName);  
  •             if (file1.exists()) {  
  •                 file1.delete();  
  •             }  
  •             //創建字節流  
  •             byte[] bs = new byte[1024];  
  •             int len;  
  •             OutputStream os = new FileOutputStream(fileName);  
  •             //寫數據  
  •             while ((len = is.read(bs)) != -1) {  
  •                 os.write(bs, 0, len);  
  •             }  
  •             //完成后關閉流  
  •             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"/>

  • 免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM