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"/>
  • 相关阅读:
    [剑指Offer] 10.矩形覆盖
    [剑指Offer] 9.变态跳台阶
    [剑指Offer] 8.跳台阶
    [剑指Offer] 7.斐波那契数列
    ArtifactTransferException: Failure to transfer org.apache.openejb:javaee-api:jar:5.0-1
    -Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HO 解决办法
    java中判断list是否为空的用法
    PL/SQL快速选中一行并执行
    substring的用法
    Oracle---------sql 中取值两列中值最大的一列
  • 原文地址:https://www.cnblogs.com/wcLT/p/8513955.html
Copyright © 2011-2022 走看看