码迷,mamicode.com
首页 > 其他好文 > 详细

获取网络资源保存本地

时间:2019-07-16 18:39:20      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:substr   try   tin   last   close   url   null   bis   pen   

public void saveToFile(String destUrl) {
       FileOutputStream fos = null;
       BufferedInputStream bis = null;
       HttpURLConnection httpUrl = null;
       URL url = null;
       intBUFFER_SIZE = 1024;
       byte[] buf = newbyte[BUFFER_SIZE];
       int size = 0;
       try {
           url = new URL(destUrl);
           httpUrl = (HttpURLConnection) url.openConnection();
           httpUrl.connect();
           bis = new BufferedInputStream(httpUrl.getInputStream());
           String fileName = destUrl.substring(destUrl.lastIndexOf("/"));
           System.out.println(fileName);
           fos = new FileOutputStream("e:\\haha.jpg");
           while ((size = bis.read(buf)) != -1) {
              fos.write(buf, 0, size);
           }
           fos.flush();
       } catch (IOException e) {
           e.printStackTrace();
       } catch (ClassCastException e) {
           e.printStackTrace();
       } finally {
           try {
              fos.close();
              bis.close();
              httpUrl.disconnect();
           } catch (IOException e) {
              e.printStackTrace();
           } catch (NullPointerException e) {
              e.printStackTrace();
           }
       }
    }

 

获取网络资源保存本地

标签:substr   try   tin   last   close   url   null   bis   pen   

原文地址:https://www.cnblogs.com/gavinYang/p/11196425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!