Java Reference
In-Depth Information
% java ContentGetter http: //www.cafeaulait.org/RelativeURLTest.class</userinput>
I got a sun . net . www . protocol . http . HttpURLConnection $HttpInputStream
</ programlisting >
Here's what happens when you try to load an audio file using getContent() :
% java ContentGetter http: //www.cafeaulait.org/course/week9/spacemusic.au
</ userinput >
I got a sun . applet . AppletAudioClip </ programlisting >
The last result is the most unusual because it is as close as the Java core API gets to a
class that represents a sound file. It's not just an interface through which you can load
the sound data.
This example demonstrates the biggest problems with using getContent() : it's hard to
predict what kind of object you'll get. You could get some kind of InputStream or an
ImageProducer or perhaps an AudioClip ; it's easy to check using the instanceof op‐
erator. This information should be enough to let you read a text file or display an image.
public final Object getContent(Class[] classes) throws IOException
A URL's content handler may provide different views of a resource. This overloaded
variant of the getContent() method lets you choose which class you'd like the content
to be returned as. The method attempts to return the URL's content in the first available
format. For instance, if you prefer an HTML file to be returned as a String , but your
second choice is a Reader and your third choice is an InputStream , write:
URL u = new URL ( "http://www.nwu.org" );
Class <?>[] types = new Class [ 3 ];
types [ 0 ] = String . class ;
types [ 1 ] = Reader . class ;
types [ 2 ] = InputStream . class ;
Object o = u . getContent ( types );
If the content handler knows how to return a string representation of the resource, then
it returns a String . If it doesn't know how to return a string representation of the re‐
source, then it returns a Reader . And if it doesn't know how to present the resource as
a reader, then it returns an InputStream . You have to test for the type of the returned
object using instanceof . For example:
if ( o instanceof String ) {
System . out . println ( o );
} else if ( o instanceof Reader ) {
int c ;
Reader r = ( Reader ) o ;
while (( c = r . read ()) != - 1 ) System . out . print (( char ) c );
r . close ();
} else if ( o instanceof InputStream ) {
int c ;
InputStream in = ( InputStream ) o ;
while (( c = in . read ()) != - 1 ) System . out . write ( c );
Search WWH ::




Custom Search