This is mind-boggling... I can make getResource() and getResourceAsStream() work properly when I run Java on my packaged JAR file that includes a text file. (for reference see the Sun docs on accessing resources) I can't seem to make the same program work properly when I am running it within Eclipse, even though I've placed my text file in the same tree as my compiled .class files
Can one of you point me at any subtleties to ensure that getResource() and getResourceAsStream() functions work properly?
I have a hunch it has to do with CLASSPATH and/or where Eclipse puts the .class files it autocompiles. (I've noticed when I run Ant, it compiles all the Java files that have changed since my last Ant build, even though Eclipse has compiled those Java files already.)
To define a breakpoint in your source code, right-click in the left margin in the Java editor and select Toggle Breakpoint. Alternatively, you can double-click on this position. The Breakpoints view allows you to delete and deactivate Breakpoints and modify their properties.
First, we need to start the Java program within Eclipse in debug mode. This can be achieved in two ways: Right-click on the editor and select Debug As -> Java Application (shown in below screenshot) Debug the program from the toolbar (highlighted in below screenshot)
A few notes:
First -- as Chocos says, put it in the eclipse source dirs, not the binary dirs. Eclipse will clear the binary dirs when you "clean", as well as clean up unmatched files. It will copy non-java source files to the binary dir.
This means that even though you drop the file in the binary dir, it may be deleted by eclipse...
Keep in mind that getResourceAsStream and getResource operate relative to the package of the code that calls them. For example:
package a.b.c;
public class Foo {
...
getClass().getClassLoader().getResourceAsStream("fee.txt");
...
}
This will actually look for a/b/c/fee.txt; the package is pre-pended. This works well if you have the fee.txt in the same source dir as the Foo.java file, or if you have a separate set of resource dirs on the classpath with the same directory structure.
If you use
...getResourceAsStream("/fee.txt");
it will look for fee.txt directly on the classpath.
When you run from the command-line, where in the JAR is the resource file? -- Scott
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With