Java Reference
In-Depth Information
URL url = new URL("http://tutortutor.ca");
}
catch (MalformedURLException murle)
{
}
would throw
java.net.MalformedURLException
(an
IOException
sub-
class).
Although you'll commonly specify
http://
as the protocol prefix, this isn't your
only choice. For example, you can also specify
file:///
when the resource is
located on the local host. Furthermore, you can prepend
jar:
to either
http://
or
file:///
when the resource is stored in a JAR file, as demonstrated here:
jar:file:///C:./rt.jar!/com/sun/beans/TypeResolver.class
The
jar:
prefixindicatesthatyouwanttoaccessaJARfileresource(e.g.,astored
classfile). The
file:///
prefix identifies the local host's resource location, which
happenstobe
rt.jar
(Java7'sruntimeJARfile)inthecurrentdirectoryontheWin-
dows C: hard drive in this example.
ThepathtotheJARfileisfollowedbyanexclamationmark(!)toseparatetheJAR
file path from the JAR resource path, which happens to be the
/com/sun/beans/
TypeResolver.class
classfileentryinthisJARfile(theleading
/
characterisre-
quired).
Note
The
URL
classinOracle'sJavareferenceimplementationsupportsadditional
protocols, including
ftp
and
mailto
.
Aftercreatinga
URL
object,youcaninvokevarious
URL
methodstoaccessportions
oftheURL.Forexample,
String getProtocol()
returnstheprotocolportionof
theURL(e.g.,
http
).Youcanalsoretrievetheresourcebycallingthe
InputStream
openStream()
method.
openStream()
createsaconnectiontotheresourceandreturnsan
InputStream
instance for reading resource data from that connection, as demonstrated here:
try (InputStream is = url.openStream())
{
int ch;
while ((ch = is.read()) != -1)