ClassLoader.getResourceAsStream

D

Digby

Hi all,

I've just written some code (see below) which relies on the
getResourceAsStream of the ClassLoader object to get a file as an
InputStream. Strangely, though it works when I run it locally, when I stick
the code and the file on a Web server, I get null returned instead. I guess
it's a classpath issue, but I thought that this method was supposed to get
round that.

Classes:

package a.b.c;
public class D {
public InputSteam getfileAsStream() {
return ClassLoader.getResourceAsStream("filename.txt");
}
}

package a.b;
public class E {
public static void main(String[] args) {
D d = new D();
System.out.println(d.getFileAsStream());
}
}

File structure:

a/b/c/D
a/b/c/filename.txt
a/b/E

I am executing E.

Any ideas? The Web server is WebSphere 3.5.

TIA

Dig
 
J

Jon Skeet

Digby said:
I've just written some code (see below) which relies on the
getResourceAsStream of the ClassLoader object to get a file as an
InputStream. Strangely, though it works when I run it locally, when I stick
the code and the file on a Web server, I get null returned instead. I guess
it's a classpath issue, but I thought that this method was supposed to get
round that.

Classes:

package a.b.c;
public class D {
public InputSteam getfileAsStream() {
return ClassLoader.getResourceAsStream("filename.txt");
}
}

That won't actually compile, as getResourceAsStream isn't a static
method. However, if you want to get it relative to the current package,
you need Class.getResourceAsStream rather than ClassLoader anyway. I'm
surprised it worked at all.

Are you sure you don't have another version of D in another jar file
somewhere? I suggest you look at what getResource("/a/b/c/D.class");
gives as a full URL, and check that it looks right.
 
D

Digby

Good point - I was actually using ClassLoader.get*System*ResourceAsStream()
which is static, but I'll try Class.getResourceAsStream() and see if it
helps.
Thanks a lot.
Dig
 
J

Jon Skeet

Digby said:
Good point - I was actually using ClassLoader.get*System*ResourceAsStream()
which is static, but I'll try Class.getResourceAsStream() and see if it
helps.

Ah - it *absolutely* will! getSystemResourceAsStream only gets
resources in the main classpath, rather than any resources loaded by
the specified classloader (or the one that loaded the class you call
getResourceAsStream on).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top