Re: Java conventions for exceptions
conrad wrote:
I have the class variable using the directory
that my class file and text file is located in.
Yet getResourceAsStream returns null.
Did you check out the Javadocs?
Each of the three classes that have a getResource() / getResourceAsStream()
resolve paths a little differently, and somewhat non-obviously in the case of
javax.servlet.ServletContext.
Let's just focus on Class's:
<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)>
The rules for searching resources associated with a given class are
implemented by the defining class loader of the class.
....
Before delegation, an absolute resource name is constructed
from the given resource name using this algorithm:
* If the name begins with a '/' ('\u002f'), then the absolute name
of the resource is the portion of the name following the '/'.
* Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object
with '/' substituted for '.' ('\u002e').
So what is "this object"? It is the class that invokes getResourceAsStream().
The package name is that of the class whose Class object we're using.
Class foo = MyClass.class.getClass();
InputStream baz = foo.getResourceAsStream("myfile.txt");
In this case the class whose Class object we're using is 'class' from
'MyClass'. That object is of type java.lang.Class. It will look based on a
package name of 'java.lang'.
Actually, this class object is of type Class < Class < MyClass >>. You really
should have used generics here! (Also, name your class something that doesn't
have the word "Class" in it.)
So the package name is taken from java.lang.Class, not your.package.My. Hence
"myfile.txt" would have to be in a subdirectory "java/lang/" of a classpath
element, and that ain't gonna happen.
You want 'foo' to be of type Class <My>, not Class <Class <My>>.
InputStream baz = My.class.getResourceAsStream( "myfile.txt" );
--
Lew