Sistema de blogs Diarium
Universidad de Salamanca
Pablo Gallardo's Blog
My professional web log about IT, Cybersecurity & Project Management

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.

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 ="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


About pmgallardo

I studied Computer Science at University of Salamanca. Since then, I have been working first as developer and then as SAP consutant. This blog is about problems I dealt when using computers, and more important, the solutions I found. Whenever I am on an issue and suddenlly I have a flash that leads me to a solution, I document my discoveries in a post.

, , , , , , , , ,

No comments yet.

Leave a Reply


Política de privacidad
Studii Salmantini. Campus de excelencia internacional