zoukankan      html  css  js  c++  java
  • android通过指定的URL地址下载文件

    public static String download(Context context,String docUrl)throws Exception{                           /***加载正文***/
            //获取存储卡路径、构成保存文件的目标路径
            String dirName = "";
            //SD卡具有读写权限、指定附件存储路径为SD卡上指定的文件夹        
            dirName = Environment.getExternalStorageDirectory()+"/Signature/";
            File f = new File(dirName);
            if(!f.exists()){      //判断文件夹是否存在
                f.mkdir();        //如果不存在、则创建一个新的文件夹
            }
            //准备拼接新的文件名
            String[] list = docUrl.split("/");
            String fileName = list[list.length-1];
            fileName = dirName + fileName;
            File file = new File(fileName);
            if(file.exists()){    //如果目标文件已经存在
                file.delete();    //则删除旧文件
            }
            //1K的数据缓冲
            byte[] bs = new byte[1024];
            //读取到的数据长度
            int len;
            try{
                //通过文件地址构建url对象
                URL url = new URL(docUrl);
                //获取链接
                //URLConnection conn = url.openConnection();
                //创建输入流
                InputStream is = url.openStream();
                //获取文件的长度
                //int contextLength = conn.getContentLength();        
                //输出的文件流
                OutputStream os = new FileOutputStream(file);
                //开始读取
                while((len = is.read(bs)) != -1){
                    os.write(bs,0,len);
                }
                //完毕关闭所有连接
                os.close();
                is.close();
            }catch(MalformedURLException e){
                fileName = null;
                System.out.println("创建URL对象失败");
                throw e;
            }catch(FileNotFoundException e){
                fileName = null;
                System.out.println("无法加载文件");
                throw e;
            }catch(IOException e){
                fileName = null;
                System.out.println("获取连接失败");
                throw e;
            }
            return fileName;
        }
  • 相关阅读:
    CentOS 7.3离线安装 JDK
    七:程序是在何种环境下运行的
    六:亲自尝试压缩数据
    五:内存和磁盘的亲密关系
    四:熟练使用有棱有角的内存
    三:计算机进行小数运算时出错的原因
    二:数据是用二进制数表示的
    一:对程序员来说CPU是什么?
    单元测试的艺术-入门篇
    蔡康永的说话之道2-透过说话,懂得把别放在心上
  • 原文地址:https://www.cnblogs.com/Yang2/p/3441010.html
Copyright © 2011-2022 走看看