I\'m loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:
/src/initialization/Life
Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.
@Test
public void testDefaultResource() {
// can we see default resources
BufferedInputStream result = (BufferedInputStream)
Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
byte [] b = new byte[256];
int val = 0;
String txt = null;
do {
try {
val = result.read(b);
if (val > 0) {
txt += new String(b, 0, val);
}
} catch (IOException e) {
e.printStackTrace();
}
} while (val > -1);
System.out.println(txt);
}
@Emracool... I'd suggest you an alternative. Since you seem to be trying to load a *.txt file. Better to use FileInputStream() rather then this annoying getClass().getClassLoader().getResourceAsStream() or getClass().getResourceAsStream(). At least your code will execute properly.
Make sure your resource directory (e.g. "src") is in your classpath (make sure it's a source directory in your build path in eclipse).
Make sure clazz is loaded from the main classloader.
Then, to load src/initialization/Lifepaths.txt, use
clazz.getResourceAsStream("/initialization/Lifepaths.txt");
Why:
clazz.getResourcesAsStream(foo) looks up foo from within the classpath of clazz, relative to the directory clazz lives in. The leading "/" makes it load from the root of any directory in the classpath of clazz.
Unless you're in a container of some kind, like Tomcat, or are doing something with ClassLoaders directly, you can just treat your eclipse/command line classpath as the only classloader classpath.
if you are using Maven make sure your packing is 'jar' not 'pom'.
<packaging>jar</packaging>
What worked for me is I placed the file under
src/main/java/myfile.log
and
InputStream is = getClass().getClassLoader().getResourceAsStream("myfile.log");
if (is == null) {
throw new FileNotFoundException("Log file not provided");
}
The default JVM classloader will use parent-classloader to load resources first:
.
Lifepaths.class.getClass()'s classloader is bootstrap classloader, so getResourceAsStream will search $JAVA_HOME only, regardless of user provided classpath. Obviously, Lifepaths.txt is not there.
Lifepaths.class 's classloader is system classpath classloader, so getResourceAsStream will search user-defined classpath and Lifepaths.txt is there.
When using java.lang.Class#getResourceAsStream(String name), name which is not start with '/' will be added with package name as prefix. If you want avoid this, please using java.lang.ClassLoader#getResourceAsStream.
For example:
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String resourceName = "Lifepaths.txt";
InputStream resourceStream = loader.getResourceAsStream(resourceName);