GetClass (). getResource () in a static context

I am 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);
    }

}

Output: "null"

I also tried StaticResource.class.getClass().getClassLoader().getResource("image.png"); , he throwsNullPointerException

I saw other solutions where it works, what am I doing wrong?

+4
source share
2 answers

Remove the .getClass () part. Just use

URL u = StaticResource.class.getResource("image.png");
+5
source

Always try to place resources outside of JAVA code to make it more manageable and reused by another package class.

You can try any

// Read from same package 
URL url = StaticResource.class.getResource("c.png");

// Read from same package 
InputStream in = StaticResource.class.getResourceAsStream("c.png");

// Read from absolute path
File file = new File("E:/SOFTWARE/TrainPIS/res/drawable/c.png");

// Read from images folder parallel to src in your project
File file = new File("images/c.jpg");

// Read from src/images folder
URL url = StaticResource.class.getResource("/images/c.png")

// Read from src/images folder
InputStream in = StaticResource.class.getResourceAsStream("/images/c.png")
0
source

Source: https://habr.com/ru/post/1539610/


All Articles