Last updated 2004-06-28 by Roedy
Green ©1996-2004 Canadian Mind Products
Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You are here : home : Java Glossary : G words : getResourceAsStream.
InputStream is = this.getClass().getResourceAsStream( "picture.gif" ); // or InputStream is = MyClass.class.getResourceAsStream( "stuff.ser" );
The resource in the jar file must be qualified with same package name as the class you call getResourceAsStream from. Alternatively, you can use an absolute name beginning with a / where dots get mapped to /s.
For example you could specify "/com/mindprod/mypackage/mystuff.ser" or "/com.mindprod.mypackage.mystuff.ser" or simply "mystuff.ser". Don't use Windows style filenames with \. These are not abitrary filenames, but resources that live along with the class files either on disk, in jars, or on the server.
In theory, getResourceAsStream will look in the local classpath, in the jar and in the directory where the class file was loaded from, though I have found in practice it is usually not that thorough. Beware, you might be getting a different copy of a file than the one in the jar you expected. In theory this should not be necessary, but test your jarred Applets with an an empty classpath.
I have seen a variety of bug reports surrounding getResource and getResourceAsStream. They sometimes can't see inside jars, see files on the server or see local files on the classpath. This is odd, since supposedly the usual classLoader mechanism does the looking, it it has much less trouble finding class files.
Netscape 4.79 getResourceAsStream has a bug. It does not properly prepend the package name on the resource. It uses it as is.
For some Satanic reason, the folk at Netscape decided that resources must have one of a magic list of extensions. .com, .exe, .dll, .dat are not among them. Happily .jpg, .gif, .ram and .ser are. To read other extensions, you must first invoke SecurityManager.enablePrivilege( "UniversalPropertyRead" ).
If getResourceAsStream does not work, check the following:
home |
Canadian Mind Products | |||
| mindprod.com IP:[24.87.56.253] | ||||
| Your IP:[80.134.30.163] | ||||
| You are visitor number 9374. | ||||
| Please send errors, omissions and suggestions | ||||
| to improve this page to Roedy Green. | ||||
| You can get a fresh copy of this page from: | or possibly from your local J: drive mirror: | |||
| http://mindprod.com/jgloss/getresourceasstream.html | J:\mindprod\jgloss\getresourceasstream.html | |||