打印一個網頁,熟悉Java網絡編程:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class URLReader { public static void main(String[] args) { System.out.println(getContent()); } private static String getContent(){ InputStream in=null; URLConnection connection=null; InputStreamReader readerStream=null; StringBuffer resultBuffer = new StringBuffer(); BufferedReader readerBuff=null; try { URL url=new URL("http://www.baidu.com"); connection = url.openConnection(); in=connection.getInputStream(); readerStream=new InputStreamReader(in); readerBuff=new BufferedReader(readerStream); String temp=null; while((temp=readerBuff.readLine())!=null){ resultBuffer.append(temp+"\n"); } if (in!=null) { in.close(); } if (readerStream != null) { readerStream.close(); } if (readerBuff != null) { readerBuff.close(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resultBuffer.toString(); } }