从URL获取文件保存到本地的代码

简介: 经常用,先放这里,用的时候过来拿!   0) {        out.write(buffer, 0, count);      }      out.
经常用,先放这里,用的时候过来拿!
 
< %@page import="java.net.*,java.io.*"%>
<%!
  public boolean saveUrlAs(String photoUrl, String fileName) {
//此方法只能用户HTTP协议
    try {
      URL url = new URL(photoUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      DataInputStream in = new DataInputStream(connection.getInputStream());
      DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
      byte[] buffer = new byte[4096];
      int count = 0;
      while ((count = in.read(buffer)) > 0) {
        out.write(buffer, 0, count);
      }
      out.close();
      in.close();
      return true;
    }
    catch (Exception e) {
      return false;
    }
  }
 
public String getDocumentAt(String urlString) {
//此方法兼容HTTP和FTP协议
    StringBuffer document = new StringBuffer();
    try {
      URL url = new URL(urlString);
      URLConnection conn = url.openConnection();
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.
          getInputStream()));
      String line = null;
      while ( (line = reader.readLine()) != null) {
        document.append(line + "/n");
      }
      reader.close();
    }
    catch (MalformedURLException e) {
      System.out.println("Unable to connect to URL: " + urlString);
    }
    catch (IOException e) {
      System.out.println("IOException when connecting to URL: " + urlString);
    }
    return document.toString();
  }
%>
<%
//测试
  String photoUrl = " http://ad4.sina.com.cn/200601/12/43932_750450.jpg";
  String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
  String filePath = "d:/ghost/";
  boolean flag = saveUrlAs(photoUrl, filePath + fileName);
  out.println("Run ok!/n<BR>Get URL file " + flag);
%>
目录
相关文章
|
1天前
|
C++
【C++】在使用代码组装URL时,一定要注意的坑......
【C++】在使用代码组装URL时,一定要注意的坑......
7 0
|
4月前
|
数据处理
Axios 默认配置 简化URL 简化代码 多台服务器接口配置
Axios 默认配置 简化URL 简化代码 多台服务器接口配置
|
7月前
|
Web App开发 数据采集 API
使用代码获得知乎文章的标题和 url
使用代码获得知乎文章的标题和 url
83 0
|
存储 Swift
Swift - Cell自适应+代码约束(SnapKit)横竖屏支持平铺+根据URL获取图片size
Swift - Cell自适应+代码约束(SnapKit)横竖屏支持平铺+根据URL获取图片size
179 0
|
安全 测试技术 Python
Tornado框架的异步代码单元支持同步获取URL在项目里实战的心得和方法
Tornado框架的异步代码单元支持同步获取URL在项目里实战的心得和方法
117 0
|
前端开发 JavaScript
tp5中前端js代码中ajax请求url问题
tp5中前端js代码中ajax请求url问题
138 0
|
数据采集 缓存 搜索推荐
SAP 电商云 Spartacus UI 有状态 的 url 和 title 属性的赋值代码
SAP 电商云 Spartacus UI 有状态 的 url 和 title 属性的赋值代码
97 0
SAP 电商云 Spartacus UI 有状态 的 url 和 title 属性的赋值代码
|
NoSQL 算法 Redis
URL 去重的 6 种方案!(附详细代码)下
URL 去重的 6 种方案!(附详细代码)下
165 0
URL 去重的 6 种方案!(附详细代码)下
|
SQL 存储 数据库
URL 去重的 6 种方案!(附详细代码)中
URL 去重的 6 种方案!(附详细代码)中
123 0
URL 去重的 6 种方案!(附详细代码)中
|
存储 SQL NoSQL
URL 去重的 6 种方案!(附详细代码)上
URL 去重的 6 种方案!(附详细代码)上
249 0
URL 去重的 6 种方案!(附详细代码)上

热门文章

最新文章