Java Reference
In-Depth Information
The
Class
class provides a
getresourceAsStream
method to simplify getting
resources from a class's class loader. The preceding code could be writ-
ten more simply as
String book = "BoldPlayer.book";
InputStream in = BoldPlayer.class.getResourceAsStream(book);
Resource names must be made up of one or more valid identifiers sep-
arated by
/
characters, specifying a path to the resource. Typically, a
class loader will search for resources in the same places it will search for
class files.
Two other resource methods
geTResource
and
getSystemResource
return
URL
objects that name the resources. The class
java.net.URL
is covered
briefly on page
725
; it provides methods to use uniform resource locat-
ors to access resources. You can invoke the
getContents
method on the
URL
objects returned by the class loader methods to get an object that
represents the contents of that
URL
.
The
getresources
method returns a
java.util.Enumeration
object (an older
variant of the
Iterator
you've seen before) that can step through
URL
ob-
jects for all the resources stored under a given name. The static method
getSystemResources
does the same for system resources.
The resource-getting methods first ask the parent class loader for the
resource, or they ask the bootstrap class loader if there is no parent. If
the resource cannot be found, then
findResource
or
findResources
is in-
voked. Just as
loadClass
is built on top of a
findClass
that you provide
when you subclass
ClassLoader
, so the resource methods are built on top
of two methods that you can override to find resources:
public URL
findResource(String name)
Returns a
URL
object for the resource of the given
name
, or
null
if none was found. If there are multiple resources of the
same name the implementation determines which should be