ProblemHaving heard these terms, you want to know the difference between a URI, URL, and URN. SolutionRead on. Or see the Javadoc for java.net.uri. DiscussionA URL is the traditional name for a network address consisting of a scheme (like "http:") and an address (site name) and resource or pathname. But there are three distinct terms in all:
Prior to 1.4, there was only a URL class; creating this class was primarily for purposes of reading from it. In 1.4, the URI class was introduced, primarily for manipulating resource identifiers, and a discussion near the end of the Java documentation for the new class explains the relationship among URI, URL, and URN. URIs form the set of all identifiers: URLs and URNs are subsets. URIs are the most general; a URI is parsed for basic syntax without regard to the scheme, if any, that it specifies, and it need not refer to a particular server. A URL includes a hostname, scheme, and other components; the string is parsed according to rules for its scheme. When you construct a URL, an InputStream is created automatically. URNs name resources but do not explain how to locate them; typical examples of URNs that you will have seen include mailto: and news: references. The main operations provided by the URI class are normalization (removing extraneous path segments including "..") and relativization (this should be called "making relative," but somebody wanted a single word to make a method name). A URI object does not have any methods for opening the URI; for that, you would normally use a string representation of the URI to construct a URL object, like so: URL x = new URL(theURI.toString( )); The program in Example 18-6 shows examples of normalization, making relative, and constructing a URL from a URI. Example 18-6. URIDemo.javapublic class URIDemo { public static void main(String[] args) throws URISyntaxException, MalformedURLException { URI u = new URI("http://www.darwinsys.com/java/../openbsd/../index.jsp"); System.out.println("Raw: " + u); URI normalized = u.normalize( ); System.out.println("Normalized: " + normalized); final URI BASE = new URI("http://www.darwinsys.com"); System.out.println("Relativized to " + BASE + ": " + BASE.relativize(u)); // A URL is a type of URI URL url = new URL(normalized.toString( )); System.out.println("URL: " + url); } } |