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"/>
  • 相关阅读:
    JSP中的选择判断 C 标签 一般与 foreach循环一块使用
    python基础学习笔记(四)
    python基础学习笔记(五)
    python基础学习笔记(六)
    python基础学习笔记(三)
    python基础学习笔记(一)
    selenium使用Xpath定位之完整篇
    Selenium Python FirefoxWebDriver处理打开保存对话框
    Selenium操作示例——鼠标悬停显示二级菜单,再点击二级菜单或下拉列表
    Selenium+Python:下载文件(Firefox 和 Chrome)
  • 原文地址:https://www.cnblogs.com/wcLT/p/8513955.html
Copyright © 2011-2022 走看看