Class.getResourceAsStream() returns null in Eclipse
Joined: Jan 17, 2006
I have the following directory structure for my project.
And source similar to:
When I run from the command line using the instruction:
it works fine. However when I try to run within Eclipse, it fails with a NullPointerExceptiion because the InputStream is null. I've tried adding the lib folder to the project classpath via Project-> Properties -> Java Build Path -> Libraries -> Add Class Folder, but the same NPE occurs. Can anyone point me in the right direction? [ July 09, 2006: Message edited by: Garrett Rowe ]
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Joined: Jan 17, 2006
Well after much handwringing and cussing, I got it to work by adding my /lib folder as a source folder via Project-> Properties -> Java Build Path -> Libraries -> Add Source Folder. This creates a copy of my resource.txt file in the bin folder which thereby ensures that it is on the classpath when I run the program. I'm not sure if this is the only/best way, but it was the only workable solution I found so far. If there is a way to add my /lib folder directly to the classpath I'd be very interested.
Java doesn't support implicit library inclusion, IDE or no. You need a class directory structure. Two possible ways are:
1. Denote a "precompiled class" directory, put your resource in that, and add it to the project classpath. This is effectively what you did, but "lib" isn't a good name for such a construct.
2. Add a build function to copy the resource into your compiled classes directory as part of the build process. This is often more trouble than it's worth, so I recommend solution #1.
What I mean by "precompiled class" directory is that unlike your compiled class directory, the precompiled classes (and resources - including images, property files, resource bundles, etc.) are not created as part of the build process, but are externally supplied and static. Since Java (and your IDE) allow multiple class sources, this makes it easy to combine the generated code and the static stuff without having the generate process nuke the static stuff.
Customer surveys are for companies who didn't pay proper attention to begin with.