通过URL链接将文件下载到本地

    public File downUrlTxt(String fileUrl){
        String fileName = DataUtils.getNumberByUUId();//调用工具类生成唯一标识文件名
        File savePath = new File(downPath);//downPath是自定义的文件下载地址,如 D://huoyun/
        if (!savePath.exists()) {//判断文件夹是否存在,不存在则创建一个叫huoyun的文件夹
            savePath.mkdir();
        }

        String[] urlname = fileUrl.split("/");//将链接地址以/剪切成字符串数组
        int len = urlname.length-1;//数组长度
        String uname = urlname[len];//获取文件名
        int i = uname.lastIndexOf(".");//最后一个.的下标
        String suf = uname.substring(i + 1);//获取文件后缀名
        try {
            File file = new File(savePath+"/"+fileName+"."+suf);//创建新文件(路径+文件名+后缀名)
            if(file!=null && !file.exists()){   //判断改文件是否存在,不存在则新创建
                file.createNewFile();
            }
            OutputStream oputstream = new FileOutputStream(file);//新建输出流
            URL url = new URL(fileUrl);//新建URL文件对象
            HttpURLConnection uc = (HttpURLConnection) url.openConnection();//创建连接
            uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true
            uc.connect();//连接启动
            InputStream iputstream = uc.getInputStream();//从远程连接获取输入流
            System.out.println("file size is:"+uc.getContentLength());//打印文件长度
            byte[] buffer = new byte[4*1024];//定义4k长的数组
            int byteRead = -1;
            while((byteRead=(iputstream.read(buffer)))!= -1){//通过输入流读取数据
                oputstream.write(buffer, 0, byteRead);//将字节数组的数据通过输出流输出
            }
            oputstream.flush();//刷新流
            iputstream.close();//关闭输入流
            oputstream.close();//关闭输出流
        } catch (Exception e) {
            System.out.println("读取失败!");
            e.printStackTrace();
        }
        System.out.println("生成文件路径:"+downPath+fileName+"."+suf);
        File file = new File(downPath + fileName+"."+suf);//获取到生成的本地文件对象
        return file;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值