Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the Java ClassLoader to load a file fromthe classpath?

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.

like image 474
Kyle Boon Avatar asked Jul 07 '09 20:07

Kyle Boon


People also ask

How do I load resources from classpath?

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.

Which ClassLoader is used to load a class?

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.

How does a ClassLoader work in Java?

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.


2 Answers

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.

like image 69
Kathy Van Stone Avatar answered Oct 02 '22 20:10

Kathy Van Stone


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");
like image 37
Yishai Avatar answered Oct 02 '22 18:10

Yishai