How to reference a File on a Java Application

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.

The method getResource() of each class allows to retrieve a file taking as a reference the path 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 ="icon.png");

Example to retrieve an image for an ImageIcon:

ImageIcon image = new ImageIcon(this.getClass().getResource("/package/sub_package/image_name.png"));

External References

Leave a Reply

Your email address will not be published. Required fields are marked *