码迷,mamicode.com
首页 > 移动开发 > 详细

Android根据URL下载文件保存到SD卡

时间:2018-03-06 14:37:00      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:byte   new   getc   tar   int   bsp   name   color   操作   

  1.  //下载具体操作  
  2.     private void download() {  
  3.         try {  
  4.             URL url = new URL(downloadUrl);  
  5.             //打开连接  
  6.             URLConnection conn = url.openConnection();  
  7.             //打开输入流  
  8.             InputStream is = conn.getInputStream();  
  9.             //获得长度  
  10.             int contentLength = conn.getContentLength();  
  11.             Log.e(TAG, "contentLength = " + contentLength);  
  12.             //创建文件夹 MyDownLoad,在存储卡下  
  13.             String dirName = Environment.getExternalStorageDirectory() + "/MyDownLoad/";  
  14.             File file = new File(dirName);  
  15.             //不存在创建  
  16.             if (!file.exists()) {  
  17.                 file.mkdir();  
  18.             }  
  19.             //下载后的文件名  
  20.             String fileName = dirName + "xiaomibianqian.apk";  
  21.             File file1 = new File(fileName);  
  22.             if (file1.exists()) {  
  23.                 file1.delete();  
  24.             }  
  25.             //创建字节流  
  26.             byte[] bs = new byte[1024];  
  27.             int len;  
  28.             OutputStream os = new FileOutputStream(fileName);  
  29.             //写数据  
  30.             while ((len = is.read(bs)) != -1) {  
  31.                 os.write(bs, 0, len);  
  32.             }  
  33.             //完成后关闭流  
  34.             Log.e(TAG, "download-finish");  
  35.             os.close();  
  36.             is.close();  
  37.         } catch (Exception e) {  
  38.             e.printStackTrace();  
  39.         }  
  40.     }  
  41. }  
  42.     String dirName = Environment.getExternalStorageDirectory() + "/MyDownLoad/";  
  43. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Android根据URL下载文件保存到SD卡

标签:byte   new   getc   tar   int   bsp   name   color   操作   

原文地址:https://www.cnblogs.com/wcLT/p/8513955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!