java 网络上下载文件

public static String downloadFile(String remoteUrl) {
    try {
        URL url = new URL(remoteUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //文件保存位置.保存在系统临时目录
        String folder = "d:/data/logs/temp/";
        File dir = new File(folder);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String fileName = getFileName(url.getPath());
        File localFile = new File(dir, fileName);
        try (
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(localFile));
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream())
        ) {
            int len = 1024;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            conn.disconnect();
        } catch (IOException e) {
            logger.error("### 下载文件{}发生异常。", localFile.getCanonicalPath(), e);
        }

        if (logger.isInfoEnabled()) {
            logger.info("### 下载文件:{}到本地:{}成功。", remoteUrl, localFile.getCanonicalPath());
        }
        return localFile.getCanonicalPath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

private static String getFileName(String remoteUrl) {
    String decode = null;
    try {
        decode = URLDecoder.decode(remoteUrl, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    File file = new File(decode);
    return file.getName();
}

 

 

调用:

 

downloadFile(url);

将远程的文件下载到本地了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值