From Gossip@Openhome

Java Gossip: URL 類別

URL 類別可以提供URL(Uniform Resource Locator)的Protocol、Host、Port、File、named anchor與URLStreamHandler等資訊,它擁有幾個建構函式,它們皆需處理MalformedURLException:
public URL(String url)
public URL(String protocol, String host, String file)
public URL(String protocol, String host, int port, String file)
public URL(URL u,String s)

URL類別可以由以下幾個方法取得資訊:
public String getProtocol()
public String getHost()
public int getPort()
public String getFile()
public String getRef()


其中getFile()會包括從主機名稱後至檔案名稱的字串,包括/,而getRef()則是取回參考點名稱,中文俗稱網頁中的「書籤」,下面這個程式示範這幾個方法的作用:
  • UrlInfo.java
package onlyfun.caterpillar;

import java.net.*;

public class UrlInfo {
public static void main(String[] args) {
try {
URL url = new URL(args[0]);
System.out.printf("URL: %s%n", url);
System.out.printf("Protocal: %s%n", url.getProtocol());
System.out.printf("Host: %s%n", url.getHost());
System.out.printf("Port: %d%n", url.getPort());
System.out.printf("File: %s%n", url.getFile());
System.out.printf("REF: %s%n", url.getRef());
}
catch(MalformedURLException e) {
e.printStackTrace();
}
}
}

當執行程式時給定的引數為https://openhome.cc:8080/admin/setup.html#justin,執行結果如下:
URL: https://openhome.cc:8080/admin/setup.html#justin
Protocal: http
Host: openhome.cc
Port: 8080
File: /admin/setup.html
REF: justin

URL類別有三個方法可以取得指定的URL資料,這三個方法必須處理IOException:
public final InputStream openStream()
public URLConnection openConnection()
public final Object getContent()


在這邊先示範openStream(),它會自動處理連線之間的協定動作,並傳回一個InputStream物件,所以可以將它塞入BufferedReader或BufferedInputStream等I/O類別,再透過它來讀取伺服器傳來的資料。

下面這個程式即利用openStream()取得指定網址的資料,並自動將資料儲存在對應檔案名稱之中,由於是使用BufferedInputStream,您可以用它來儲存HTML網頁,也可以儲存圖片:
  • UrlInfo.java
package onlyfun.caterpillar;

import java.io.*;
import java.net.*;

public class Download {
public static void main(String[] args) {
try {
URL url = new URL(args[0]);
String fileName = url.getFile().substring(
url.getFile().lastIndexOf('/') + 1);

BufferedInputStream inputStream =
new BufferedInputStream(url.openStream());
BufferedOutputStream outputStream =
new BufferedOutputStream(
new FileOutputStream(fileName));

int read = 0;
while((read = inputStream.read()) != -1) {
outputStream.write(read);
}

inputStream.close();
outputStream.flush();
outputStream.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}