I want to use the ClassLoader to load a properties file for the Properties class. I've simplified the below code to remove error handling for the purposes of this discussion:
loader = this.getClass().getClassLoader();
in = loader.getResourceAsStream("theta.properties");
result = new Properties();
result.load(in);
In the same directory as this class I have the file "theta.properties" but the InputStream is always null. Am I putting the file in the wrong place? I'm using eclipse and its set to build the class files to the source folder - so that shouldn't be the problem.
I can't find anything in the JavaDoc to get the ClassLoader to tell me what classpath is being searched.
We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.
Types of ClassLoaders in Java To know the ClassLoader that loads a class the getClassLoader() method is used. All classes are loaded based on their names and if any of these classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException.
Class loaders are responsible for loading Java classes dynamically to the JVM (Java Virtual Machine) during runtime. They're also part of the JRE (Java Runtime Environment). Therefore, the JVM doesn't need to know about the underlying files or file systems in order to run Java programs thanks to class loaders.
By using getClass().getClassloader()
you look for "theta.properties" from the root path directory. Just use getClass().getResourceAsStream()
to get a resource relative to that class.
If the file is in the same directory as the class, you have to prefix the class's package as a directory.
So if your package is:
package com.foo.bar;
Then your code is:
.getResourceAsStream("com/foo/bar/theta.properties");
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