java实现下载文件到指定目录(项目亲测)

下载文件到指定目录

/**
	 * 下载文件到指定目录
	 * @param dowUrl:http地址
	 * @param  dowPath:指定目录
	 * */
    public static String download(String dowUrl, String dowPath){
        try {
		log.info("下载地址是:"+dowUrl+",存储地址是:"+dowPath);
            URL url = new URL(dowUrl);

            URLConnection urlConnection = url.openConnection();

            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;// http的连接类

            //String contentType = httpURLConnection.getContentType();//请求类型,可用来过滤请求,

            httpURLConnection.setConnectTimeout(1000*5);//设置超时

            httpURLConnection.setRequestMethod("POST");//设置请求方式,默认是GET

            httpURLConnection.setRequestProperty("Charset", "UTF-8");// 设置字符编码

            httpURLConnection.connect();// 打开连接

            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

            String path = dowPath;// 指定存放位置
            File filed = new File(path);

            OutputStream out = new FileOutputStream(filed);
            int size = 0;

            byte[] b = new byte[2048];
            //把输入流的文件读取到字节数据b中,然后输出到指定目录的文件
            while ((size = bin.read(b)) != -1) {
                out.write(b, 0, size);
            }
            // 关闭资源
            bin.close();
            out.close();
			return "200";
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "500";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
			return "400";
        }
    }

有问题可以留言,大家一起探讨,自己测试没有问题。

  • 3
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋秋秋秋秋雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值