Java Reference
In-Depth Information
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 13-10
shows examples of normalizating, making relative, and con-
structing a URL from a URI.
Example 13-10. URIDemo.java
public
public class
class
URIDemo
URIDemo
{
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
URISyntaxException
,
MalformedURLException
{
URI u
=
new
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
final
URI BASE
=
new
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
new
URL
(
normalized
.
toString
());
System
.
out
.
println
(
"URL: "
+
url
);
// Junk
URI uri
=
new
new
URI
(
"bean:WonderBean"
);
System
.
out
.
println
(
uri
);
}
}