zoukankan      html  css  js  c++  java
  • Android根据URL下载文件保存到SD卡

    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"/>
  • 相关阅读:
    java日期格式转换工具类
    关于IOS给我的启发
    (转载)小米手机给我的启发和思考
    ElasticDownload
    ShopMall
    CycleViewPager
    MaterialImageView
    ZrcListView
    superCleanMaster
    QuickNewsLibs
  • 原文地址:https://www.cnblogs.com/wcLT/p/8513955.html
Copyright © 2011-2022 走看看