java实现从网上下载文件到本地

基本实现步骤:

1.建立http连接,获取对象 connection

2.输入流读文件

3.新建存储路径

4.输出流写入数据,并关闭流

public class test {

public static void main(String[] args) {
getInternetRes("D:\\demoefile","http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=3d2175db3cd3d539d530078052ee8325/b7003af33a87e950c1e1a6491a385343fbf2b425.jpg","112.jpg");

}

public static void getInternetRes(String newUrl, String oldUrl, String fileName) {
        URL url = null;
        HttpURLConnection con = null;
        InputStream in = null;
        FileOutputStream out = null;
        try {
             url = new URL(oldUrl);
           //建立http连接,得到连接对象
           con = (HttpURLConnection) url.openConnection();
           //输入流读取文件
           in = con.getInputStream();
           //转化为byte数组
           byte[] data = getByteData(in);
           //建立存储的目录、保存的文件名 
           File file = new File(newUrl+today);
           if (!file.exists()) {
               file.mkdirs();
           }
           //修改文件名   用id重命名
           File res = new File(file + File.separator + fileName);
           //写入输出流
           out = new FileOutputStream(res);
           out.write(data);
          logger.info("下载 successfully!");
       } catch (MalformedURLException e) {
        logger.error("下载出错!"+e.toString());
       } catch (IOException e) {
        logger.error("下载出错!"+e.toString());
       } finally {
        //关闭流
           try {
               if (null != out)
                   out.close();
               if (null != in)
                   in.close();
           } catch (IOException e) {
            logger.error("下载出错!"+e.toString());
           }
       }
}
return null;
}

/**

* @Title: getByteData
* @Description: 从输入流中获取字节数组
* @author zml
* @date Sep 12, 2017 7:38:57 PM
*/
private static byte[] getByteData(InputStream in) throws IOException {
       byte[] b = new byte[1024];
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
       int len = 0;
       while ((len = in.read(b)) != -1) {
           bos.write(b, 0, len);
       }
       if(null!=bos){
           bos.close();
       }
       return bos.toByteArray();
   }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值