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

文章作者 100test 发表时间 2007:03:14 16:26:18
来源 100Test.Com百考试题网


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 = "/Files/BeyondPic/2006715/957165989.jpg".
   String fileName = photoUrl.substring(photoUrl.lastIndexOf("/")).
   String filePath = "d:/ghost/".
   boolean flag = saveUrlAs(photoUrl, filePath fileName).
   out.println("Run ok!\n
Get URL file " flag).
  %>

相关文章


Jsp学习笔记[10]-JSP标签库(一)
Jsp学习笔记[10]-JSP标签库(二)
从URL获取文件保存到本地的代码
Java5.0多线程编程实践
Java网络编程-JavaSocket编程(三)
澳大利亚华人论坛
考好网
日本华人论坛
华人移民留学论坛
英国华人论坛