网络文件下载

这是我自己写的文件下载:

如果下载链接中有汉字,请先对汉字部分进行转码 在进行文件下载,注意在线程中下载文件,

单下载文件

 /**
     * 下载文件
     *
     * @param downloadURL 要下载的文件网络路径
     */
    private void downloadFile(String downloadURL) {
        FileOutputStream outputStream=null;
        InputStream inputStream=null;
        try {
            if (downloadURL == null) {
                Log.e("download", "脉盘下载文件的链接地址为空");
                return;
            }
            //获取SD卡的根目录
            String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
            //你要把文件下载到那个文件夹,targetDir就这个文件夹的名称
            File rootFolder = new File(absolutePath + "/targetDir");
            if (!rootFolder.exists()) {
                rootFolder.mkdirs();
            }
            File folder = new File(absolutePath + "/targetDir");
            if (!folder.exists()) {
                folder.mkdirs();
            }
            //如果这个文件是MP4文件,后缀名suffix=.mp4
            String suf = ".mp4";
            //文件的名字
            String fileName = "myVideo";
            String saveFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/targetDir" + fileName + suf;

            URL url = new URL(downloadURL);
            //打开连接
            URLConnection conn = url.openConnection();
            //打开输入流
             inputStream = conn.getInputStream();
            //获得长度
            final int contentLength = conn.getContentLength();
            //先在本地看下这个文件存不存在,
            File destinationFile = new File(saveFileName);
            if (destinationFile.exists()) {
                //如果存在就把他删了,避免下载的文件和原来已有的文件重复了
                destinationFile.delete();
            }
            //创建字节流
            byte[] bs = new byte[1024];
            int len;
             outputStream = new FileOutputStream(destinationFile);
            int mSize = 0;
            //写数据
            while ((len = inputStream.read(bs)) != -1) {
                //已下载数据大小
                mSize += len;
                outputStream.write(bs, 0, len);
            }
            //下载完成
            Log.e("download","下载完成,文件保存在:"+saveFileName+"这个路径");
        } catch (IOException e) {
            //如果下载失败了,就会打印日志
           Log.e("download","下载文件异常msg:" + e.getMessage());
            e.printStackTrace();
        } finally {
            //不管有没有下载成功都要把流关掉
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
posted @ 2017-12-22 14:42  RockSmall  阅读(204)  评论(0编辑  收藏  举报