手机版
你好,游客 登录 注册
背景:
阅读新闻

如何使用Java读取Web页面

[日期:2012-05-06] 来源:Linux社区  作者:huoyin [字体:大 中 小]

如何使用Java读取Web页面:

  1. import static java.lang.System.out;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.FileWriter;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.net.URL;  
  10.   
  11.   
  12. public class HtmlHelper {  
  13.       
  14.     private static String urlstring = "http://www.csdn.net";  
  15.     private static String filename = "C:/tmp/csdn.html";  
  16.       
  17.     public static void main(String[] args){  
 
  1. //comment out the following section to add proxy server support  
 
  1.          //System.setProperty("http.proxyHost",conf.proxyhost);   
  2.         //System.setProperty("http.proxyPort",conf.proxyport);   
  3.   
  4.         InputStream is = null;  
  5.         BufferedReader br = null;  
  6.         BufferedWriter bw = null;  
  7.         try {  
  8.             out.println("Downloading html page from " + urlstring);  
  9.             URL url = new URL(urlstring);  
  10.             is = url.openStream(); // throws an IOException   
  11.             br = new BufferedReader(new InputStreamReader(is));  
  12.             bw = new BufferedWriter(new FileWriter(filename));  
  13.             String line = null;  
  14.             while ((line = br.readLine()) != null) {  
  15.                 bw.write(line);  
  16.                 bw.newLine();  
  17.             }  
  18.             bw.flush();  
  19.             out.println("Downloaded to " + filename);  
  20.         } catch (IOException ioe) {  
  21.             ioe.printStackTrace();  
  22.         } finally {  
  23.             try {if (is != null) {is.close();}} catch (IOException ignore) {}  
  24.             try {if (br != null) {br.close();}} catch (IOException ignore) {}  
  25.             try {if (bw != null) {bw.close();}} catch (IOException ignore) {}  
  26.         }  
  27.     }  
  28. }  
linux
相关资讯       Java教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款