服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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

<%@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 = "/upfile/2007-11/20071116223721780.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);
%>

(t006)


扫描关注微信公众号