• 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"/>
  • 相关阅读:
    HDU 2809 God of War(DP + 状态压缩)
    POJ 3311 Hie with the Pie(DP状态压缩+最短路径)
    HDU 1400 (POJ 2411 ZOJ 1100)Mondriaan's Dream(DP + 状态压缩)
    位运算的应用
    ZOJ 3471 Most Powerful(DP + 状态压缩)
    POJ 2039 To and Fro(模拟)
    UVA 10817 Headmaster's Headache(DP +状态压缩)
    黑子的篮球
    POJ 1564(HDU 1258 ZOJ 1711) Sum It Up(DFS)
    HDU 3006 The Number of set(位运算 状态压缩)
  • 原文地址:https://www.cnblogs.com/wcLT/p/8513955.html
Copyright © 2020-2023  润新知