I am developing a small Gui Application and want to load my Images from the resource folder. This does work on Windows, but on Linux (Ubuntu 19.04 and Raspbian Buster) it does not.
I've been trying to switch from
getClass().getResource("black.jpg").getFile()
to
getClass().getClassLoader().getResource("black.jpg").getFile()
This is my View Class, extending from JFrame (shorted)
public View() {
try {
bI = ImageIO.read(new File(getClass().getClassLoader().getResource("black.jpg").getFile()));
} catch (IOException e) {
e.printStackTrace();
}
[...]
contentPane = new BackgroundPanel(bI);
Error Message in terminal:
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at de.grapatin.escaperoom.view.View.<init>(View.java:38)
at de.grapatin.escaperoom.controller.Controller.<init
(Controller.java:11)
at de.grapatin.escaperoom.App.main(App.java:11)
I expect the image to be shown, but it does not happen. The background is black (like the image black.jpg in my code) but exchanging it does not solve the problem.
Project Structure:
─src
│ ├───main
│ │ ├───java
│ │ │ └───de
│ │ │ └───marvin
│ │ │ └───uitest
│ │ │ ├───controller
│ │ │ ├───model
│ │ │ │ └───enums
│ │ │ ├───util
│ │ │ └───view
│ │ └───resources
│ │ └───images
The output of
System.out.println(getClass().getResource("/black.jpg").getFile());
is
file:/C:/Users/marvin/uitest/target/uitest-0.0.1-SNAPSHOT.jar!/black.jpg
The ! does not come from my side
I just discovered that Windows does also not read from the Image File from the jar. But it is there in the root of the folder.
This question is not a duplicate of the following: imageio.IIOException: Can't read input file because the accepted Answer does not work in my case and the syntax is entirely different and against the accepted answer in my question. Also the edit does not clearly show how to adapt the solution.