When referencing resources in a Java project, as for example photos, sound clips, video, etc., it is important to do it correctly because otherwise we may find errors when executing the application out of the IDE from a JAR file or on a different operating systems.
Method getResource on each class allows to retrieve a file taking as a reference the route where this class is located. Example: MyClass.getResource(“file.ext”);
In order to export code more easily, instead of writing each time the class name (MyClass…) depending of the file, some developers use the method this.getClass(), that returns always the current class.
BufferedImage bImage = ImageIO.read(this.getClass().getResource("icon.png");
Example to retrieve an image for an ImageIcon:
ImageIcon image = new ImageIcon(this.getClass().getResource("/package/sub_package/image_name.png"));
Example to retrieve an image for an ImageIO:
External References
- “Loading resources like images while running project distributed as JAR archive“; stackoverfliow
- “Referencing an image in a JAR file“; stackoverflow
- “this.getClass().getResource(“”).getPath() returns an incorrect path“; stackoverflow
https://stackoverflow.com/questions/9864267/loading-resources-like-images-while-running-project-distributed-as-jar-archive/9866659#9866659
No comments yet.