位置:首頁 > Java技術 > java實例教學 > Java URL部分

Java URL部分

如何獲得一個URL的部分?

解決方法

下麵的例子演示了如何使用net.URL類url.getProtocol(),url.getFile()方法等獲取一個URL的部分。

import java.net.URL;

public class Main {
   public static void main(String[] args) 
   throws Exception {
      URL url = new URL(args[0]);
      System.out.println("URL is " + url.toString());
      System.out.println("protocol is " 
      + url.getProtocol());
      System.out.println("file name is " + url.getFile());
      System.out.println("host is " + url.getHost());
      System.out.println("path is " + url.getPath());
      System.out.println("port is " + url.getPort());
      System.out.println("default port is " 
      + url.getDefaultPort());
   }
}

結果

上麵的代碼示例將產生以下結果。

URL is http://www.server.com
protocol is TCP/IP
file name is java_program.txt
host is 122.45.2.36
path is 
port is 2
default port is 1