Java Reference
In-Depth Information
The
java.io.File
class has a
toURL()
method that returns a
file
URL matching the
given file. The exact format of the URL returned by this method is platform dependent.
For example, on Windows it may return something like
file:/D:/JAVA/JNP4/05/
ToURLTest.java
. On Linux and other Unixes, you're likely to see
file:/home/elharo/
books/JNP4/05/ToURLTest.java
. In practice,
file
URLs are heavily platform and pro‐
gram dependent. Java file URLs often cannot be interchanged with the URLs used by
web browsers and other programs, or even with Java programs running on different
platforms.
Class loaders are used not only to load classes but also to load resources such as images
and audio files. The static
ClassLoader.getSystemResource(String name)
method
returns a
URL
from which a single resource can be read. The
ClassLoader.getSystem
Resources(String name)
method returns an
Enumeration
containing a list of
URL
s
from which the named resource can be read. And finally, the instance method
getRe
source(String name)
searches the path used by the referenced class loader for a URL
to the named resource. The URLs returned by these methods may be file URLs, HTTP
URLs, or some other scheme. The full path of the resource is a package qualified Java
name with slashes instead of periods such as
/com/macfaq/sounds/swale.au
or
com/
macfaq/images/headshot.jpg
. The Java virtual machine will attempt to find the requested
resource in the classpath, potentially inside a JAR archive.
There are a few other methods that return
URL
objects here and there throughout the
class library, but most are simple getter methods that return a URL you probably already
know because you used it to construct the object in the first place; for instance, the
getPage()
method of
javax.swing.JEditorPane
and the
getURL()
method of
java.net.URLConnection
.
Retrieving Data from a URL
Naked URLs aren't very exciting. What's interesting is the data contained in the docu‐
ments they point to. The
URL
class has several methods that retrieve data from a URL:
public
InputStream
openStream
()
throws
IOException
public
URLConnection
openConnection
()
throws
IOException
public
URLConnection
openConnection
(
Proxy
proxy
)
throws
IOException
public
Object
getContent
()
throws
IOException
public
Object
getContent
(
Class
[]
classes
)
throws
IOException
The most basic and most commonly used of these methods is
openStream()
, which
returns an
InputStream
from which you can read the data. If you need more control
over the download process, call
openConnection()
instead, which gives you a
URLCon
nection
which you can configure, and then get an
InputStream
from it. We'll take this
up in
Chapter 7
. Finally, you can ask the
URL
for its content with
getContent()
which
may give you a more complete object such as
String
or an
Image
. Then again, it may
just give you an
InputStream
anyway.