得到一个网页的内容(命令方式和文本方式)

1  命令方式

import java.net.*;

import java.io.*;



public class OpenUrl

{

public OpenUrl(){}

public void getContent(String strUrl)



{

   try{

   

    URL url=new URL(strUrl);

    BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));

    String s="";



    while((s=br.readLine())!=null)

    {     

      System.out.println(s+"/r/n"); 

  

    }

    br.close();

    

   }

   catch(Exception e){

    

   

   }  

}



public static void main(String args[])

{

   //具体使用方法

   OpenUrl ou=new OpenUrl();

   ou.getContent(http://www.baidu.com);

}



}
2 将内容保存到一个文本文件中
package cdsb.cdt.swort;

import java.io.*;

import java.net.*;



import org.dom4j.Document;

import org.dom4j.DocumentException;

//import org.dom4j.io.OutputFormat;

import org.dom4j.io.SAXReader;

//import org.dom4j.io.XMLWriter;







public class ClientManager 

{

private  String url;

private  String xmlName;

public ClientManager( String url,String xmlName)

{

	this.url=url;

	this.xmlName=xmlName;//相对路径加文件名

	}

//进行xml文件的保存

   public Boolean SaveXml() 

   {

	             Boolean bool=false;

	           //进行相应xml文件的保存



		        try

		        {

	            URL url1 = new URL(url);

		        BufferedReader br=new BufferedReader(new InputStreamReader(url1.openStream()));

			    String s;

                File file = new File(xmlName); 

			

			    FileOutputStream fos=new FileOutputStream(file); 



			    DataOutputStream out=new  DataOutputStream(fos);

			    //OutputFormat format = OutputFormat.createPrettyPrint();

	            //format.setEncoding("GBK");    // 指定XML编码        

	            //XMLWriter writer = new XMLWriter(new FileWriter(xmlName),format);

			    //writer.write(s);

			    //writer.close();

			  

			    while((s=br.readLine())!=null)

			    {     

			       out.writeBytes(s);

			    }

			    br.close();

			  

			   

		        bool=true;

		        }

		        catch(IOException ex)

		        {

		        	return false;

		        	

		        }



	          return bool;

	   

   }

 

   public static void main(String [] args)

   {

               ClientManager  cm=new ClientManager("http://www.baidu.com","result.xml");

                cm.SaveXml();

              

   }
}
注意:第2种方法保存如果有中文的话 可能会出现乱码.


 

你可能感兴趣的:(exception,xml,String,File,url,import)