1 Problem Description

From the source runtime, resource files are typically read as follows:

String str = "1.jpg";
Copy the code

Resource files are placed in the same directory as source files, or have the same parent directory:

String str = "a/b/1.jpg";
Copy the code

This direct compilation run no problem, but into the JAR package will not read, directly throw null pointer exception.

2 Solutions

Read with a URL or InputStream:

URL url = getClass().getClassLoader().getResource("a/b/1.jpg");
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("a/b/1.png");
Copy the code

Note that the path cannot be preceded by / :

URL url = getClass().getClassLoader().getResource("/a/b/1.jpg");
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/a/b/1.png");
Copy the code

This reads null. GetClass ().getClassLoader().getResource() runs from the source URL as follows:

URL

file:
jar:file:
URL
Swing
JFrame

mainFrame.setIconImage(new ImageIcon(getClass().getClassLoader().getResource("image/icon.png")).getImage());
Copy the code

If the path can only be handled by String, you need to remove the prefix file: or jar:file:, which can be read with the JarFile class.