java 读取网站的源代码

package html;   

  

import java.io.BufferedReader;   

import java.io.File;   

import java.io.FileOutputStream;   

import java.io.InputStream;   

import java.io.InputStreamReader;   

import java.net.HttpURLConnection;   

import java.net.URL;   

  

public class ReaderPageByUrl {   

 /**  

  * 根据网址读取网页HTML内容  

  * @param pageUrl 网页地址  

  */  

 public String readerPageByUrl(String pageUrl) {   

  URL url;   

     String pageString="";   

  try {   

   url = new URL(pageUrl);   

   HttpURLConnection connection = (HttpURLConnection) url   

     .openConnection();   

   InputStream is = connection.getInputStream();   

   BufferedReader br = new BufferedReader(new InputStreamReader(is));   

   StringBuffer sb=new StringBuffer();   

   String line = null;   

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

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

   }   

   pageString=sb.toString();   

  } catch (Exception e) {   

   e.printStackTrace();   

  }finally{   

      

  }   

  return pageString;   

 }   

 /**  

  * 写入操作  

  * @param filePath 静态页面路径  

  * @param fileStr  网页内容  

  * @throws Exception  

  */  

 public void writeStringToFile(String filePath, String fileStr) throws Exception   

 {   

  File file=new File(filePath);    

  FileOutputStream fileout = new FileOutputStream(file);   

   fileout.write(fileStr.getBytes());   

   fileout.close();   

 }   

 /**  

  * 生成静态页面  

  * @param pageUrl  网址  

  * @param filePath 静态页面路径  

  * @throws Exception   

  */  

 public void createStaticPage(String pageUrl,String filePath) throws Exception{   

  //获取网页内容   

  String pageStr=readerPageByUrl(pageUrl);   

  try {   

   writeStringToFile(filePath, pageStr);   

  } catch (Exception e) {   

   e.printStackTrace();   

  }   

     

 }   

    //测试   

 public static void main(String[] args) {   

  ReaderPageByUrl rb=new ReaderPageByUrl();   

  String pageUrl="http://www.g.cn/";   

  String filePath="D://static.htm";   

     try {   

   rb.createStaticPage(pageUrl, filePath);   

  } catch (Exception e) {   

   // TODO Auto-generated catch block   

   e.printStackTrace();   

  }   

 }   

  

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值