在 java 中從 URL 連線讀寫有哪些關鍵步驟?
java.net 包中的 URL 類表示一個統一資源定位符,用於指向全球資訊網中的資源(檔案或目錄或引用)。
這個類提供各種建構函式,其中一個接受 String 引數並構造 URL 類的物件。
這個類的 openStream() 方法開啟到當前物件表示的 URL 的連線,並返回一個 InputStream 物件,使用該物件可以從 URL 讀取資料。
因此,要從網頁中讀取資料(使用 URL 類),需要執行以下操作:
透過將所需網頁的 URL 作為其建構函式的引數傳遞來例項化 java.net.URL 類。
呼叫 openStream() 方法並檢索 InputStream 物件。
透過將上述檢索到的 InputStream 物件作為引數傳遞來例項化 Scanner 類。
示例
import java.io.IOException; import java.net.URL; import java.util.Scanner; public class ReadingWebPage { public static void main(String args[]) throws IOException { //Instantiating the URL class URL url = new URL("http://www.something.com/"); //Retrieving the contents of the specified page Scanner sc = new Scanner(url.openStream()); //Instantiating the StringBuffer class to hold the result StringBuffer sb = new StringBuffer(); while(sc.hasNext()) { sb.append(sc.next()); //System.out.println(sc.next()); } //Retrieving the String from the String Buffer object String result = sb.toString(); System.out.println(result); //Removing the HTML tags result = result.replaceAll("<[^>]*>", ""); System.out.println("Contents of the web page: "+result); } }
輸出
<html><body><h1>Itworks!</h1></body></html> Contents of the web page: Itworks!
廣告