I'm trying to get a resource (image.png, in the same package as this code) from a static method using this code:
import java.net.*;
public class StaticResource {
public static void main(String[] args) {
URL u = StaticResource.class.getClass().getResource("image.png");
System.out.println(u);
}
}
The output is just 'null'
I've also tried StaticResource.class.getClass().getClassLoader().getResource("image.png");
, it throws a NullPointerException
I've seen other solutions where this works, what am I doing wrong?
Class class getResource () method: Here, we are going to learn about the getResource () method of Class class with its syntax and example. getResource () method is available in java.lang package. getResource () method is used to return the URL (Uniform Resource Locator) with the given resource name.
Tags:java| properties file| resources To call getResourceAsStreamin a static method, we use ClassName.classinstead of getClass() 1. In non static method getClass().getClassLoader().getResourceAsStream("config.properties")) 2. In static method ClassName.class.class.getClassLoader().getResourceAsStream("config.properties")) 1. Non Static Method
Return Value: This method returns the specified resource of this class in the form of InputStream objects. Exception This method throws: Below programs demonstrate the getResourceAsStream () method.
The getResource () method of java.lang.Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of URL object. Parameter: This method accepts a parameter resourceName which is the resource to get.
Remove the ".getClass()" part. Just use
URL u = StaticResource.class.getResource("image.png");
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