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

<%@pageimport="java.net.*,java.io.*"%>

  <%!

  publicbooleansaveUrlAs(StringphotoUrl,StringfileName){

  //此方法只能用户HTTP协议

  try{

  URLurl=newURL(photoUrl);

  HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();

  DataInputStreamin=newDataInputStream(connection.getInputStream());

  DataOutputStreamout=newDataOutputStream(newFileOutputStream(fileName));

  byte[]buffer=newbyte[4096];

  intcount=0;

  while((count=in.read(buffer))>0){

  out.write(buffer,0,count);

  }

  out.close();

  in.close();

  returntrue;

  }

  catch(Exceptione){

  returnfalse;

  }

  }  

  publicStringgetDocumentAt(StringurlString){

  //此方法兼容HTTP和FTP协议

  StringBufferdocument=newStringBuffer();

  try{

  URLurl=newURL(urlString);

  URLConnectionconn=url.openConnection();

  BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.

  getInputStream()));

  Stringline=null;

  while((line=reader.readLine())!=null){

  document.append(line+"\n");

  }

  reader.close();

  }

  catch(MalformedURLExceptione){

  System.out.println("UnabletoconnecttoURL:"+urlString);

  }

  catch(IOExceptione){

  System.out.println("IOExceptionwhenconnectingtoURL:"+urlString);

  }

  returndocument.toString();

  }

  %>

  <%

  //测试

  StringphotoUrl="http://ad4.sina.com.cn/200601/12/43932_750450.jpg";

  StringfileName=photoUrl.substring(photoUrl.lastIndexOf("/"));

  StringfilePath="d:/ghost/";

  booleanflag=saveUrlAs(photoUrl,filePath+fileName);

  out.println("Runok!\n
GetURLfile"+flag);

  %>

你可能感兴趣的:(java,.net)