Using a class from the class library

You use the java.net.URL class just like you'd use any other class with these methods that happens to be named java.net.URL. For example,

public class URLSplitter {

  public static void main(String[] args) {
   
    for (int i = 0; i < args.length; i++) {
      try {
        java.net.URL u = new java.net.URL(args[i]);
        System.out.println("Protocol: " + u.getProtocol());
        System.out.println("Host: "     + u.getHost());
        System.out.println("Port: "     + u.getPort());
        System.out.println("File: "     + u.getFile());
        System.out.println("Ref: "      + u.getRef());
      }
      catch (java.net.MalformedURLException ex) {
        System.err.println(args[i] + " is not a valid URL");
      }
    }

  } 

}

Here's the output:

$ java URLSplitter http://www.poly.edu
Protocol: http
Host: www.poly.edu
Port: -1
File: /
Ref: null

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999, 2003 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified October 13, 2003