You can use the getResourceAsStream() method of java.lang.Class , as you did, but before you go, you need to add / .
This question is complicated.
1. Two methods with the same name
First of all, there are two methods of the same name and the same signature in these two classes:
java.lang.Class java.lang.ClassLoader
They have the same name: getResource(String) (and getResourceAsStream(String) same).
2. They accept different format parameters
Then their parameter has a different format:
- The
java.lang.Class.getResouce<asStream>() method takes a path with and without a leading / , which leads to various resource search strategies. If the path does not have / , Java will look for the resource in the folder / folder where the .class file is located. If it has / , Java will start searching from the root of the classpath. The java.lang.ClassLoader.getResource<asStream>() method accepts only the path without / , because it always looks for the class path. In a path based on classpath / not a valid character. *
*: This answer says: this.getClass (). getClassLoader (). getResource ("...") and NullPointerException
How to add a folder to classpath? In Eclipse, we enable the project context menu: "Build Path" - "Configure Build Path ..." and add a folder to create the path.
3. When it comes to Maven
Finally, if the project is a Maven project, by default src/main/resources is in the classpath, so we can use
Class.getResource("/path-to-your-res");
or,
ClassLoader.getResource("path-to-your-res");
to load something under src/main/resources .
If we want to add another resource folder, as you already mentioned, this is done in pom.xml . And they are also added to the classpath made by Maven. No additional configuration is required.
4. Example
For example, if your config.ini is under src/main/resources/settings , myAvatar.gif in the src/main/images section, you can do:
In pom.xml :
<build> <resources> <resource> <directory>src/main/images</directory> </resource> </resources> </build>
In code:
URL urlConfig = MyClass.class.getResource("/settings/config.ini"); //by default "src/main/resources/" is in classpath and no config needs to be changed. InputStream inputAvatar = MyClass.class.getResourceAsStream("/myAvatar.gif"); //with changes in pom.xml now "src/main/images" is counted as resource folder, and added to classpath. So we use it directly.
We must use / above.
Or, with ClassLoader:
URL urlConfig = MyClass.class.getClassLoader().getResource("settings/config.ini"); //no leading "/"!!! InputStream inputAvatar = MyClass.class.getClassLoader().getResourceAsStream("myAvatar.gif"); //no leading "/"!!!