Java实现文件下载

public  void downloadFile(String filesPath,String FileName,String url) throws IOException {
        String folderPath = filesPath;
        File folder = new File(folderPath);
        // 如果文件夹不存在,则创建
        if (!folder.exists()) {
            boolean created = folder.mkdirs();
            if (created) {
                log.info("成功创建文件夹:" + folderPath);
            } else {
                log.info("创建文件夹失败:" + folderPath);
            }
        }
        URL url = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 从响应中获取输入流
            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = folderPath + "\\" + fileName;
            // 打开本地文件输出流
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);
            // 复制文件内容到本地文件
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();
            log.info(fileName+"保存成功");
        } else {
            log.info("下载失败,HTTP响应代码: " + responseCode);
        }
        httpConn.disconnect();
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值