为了表示URL, java.net中实现了类URL。我们可以通过下面的构造方法来初始化一个URL对象:
(1) public URL (String spec);
通过一个表示URL地址的字符串可以构造一个URL对象。
URL urlBase=new URL("http://www. 263.net/")
(2) public URL(URL context, String spec);
通过基URL和相对URL构造一个URL对象。
URL net263=new URL ("http://www.263.net/");
URL index263=new URL(net263, "index.html")
(3) public URL(String protocol, String host, String file);
new URL("http", "www.gamelan.com", "/pages/Gamelan.net.
html");
(4) public URL(String protocol, String host, int port, String
file);
URL gamelan=new URL("http", "www.gamelan.com",
80, "Pages/Gamelan.network.html");
注意:类URL的构造方法都声明抛弃非运行时例外(MalformedURLException),因此生成URL对象时,我们必须要对这一例外进行处理,通常是用try-catch语句进行捕获。格式如下:
try{
URL myURL= new URL(…)
}catch (MalformedURLException e){
…
//exception handler code here
…
}
|