0

I'm working in java swing application. I'm using icon images which is placed inside uploads folder. When i run my project it's working fine.

I export my project as jar. When i run my jar file it show file not found error.

This is my code,

BufferedImage img = ImageIO.read(new File(Config.IMAGE_RESOURCE_FOLDER + "/" + fileName)); 

folder structure

10
  • 1
    Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL. Commented Sep 27, 2018 at 6:00
  • BTW - what is the value of Config.IMAGE_RESOURCE_FOLDER (what path does it point to)? Commented Sep 27, 2018 at 6:02
  • Config.IMAGE_RESOURCE_FOLDER = "images" Commented Sep 27, 2018 at 6:09
  • I'm using this functionality inside static method. So when i use this.getClass().getResource("/path/to/the.resource"); it's not working. Instead of this i tried with sttic method class also. But not working. Commented Sep 27, 2018 at 6:10
  • Your code is currently looking for a file located in the directory ./images, where . is the current directory, i.e. the directory from which the java program was started. So, if you didn't execute Java from the right directory, or if your images are in a folder named uploads, it can't possibly work. Commented Sep 27, 2018 at 6:17

1 Answer 1

1

I assume your File is in the jar. So put a class named Locator in the same Directory. and use following code:

URL url = locator.getURL(name + ".gif"); Image img = Toolkit.getDefaultToolkit().getImage(url);

The class Locator is:

package schachfiguren; import java.net.*; public class Locator { public URL getURL(String pfad) { URL url = this.getClass().getResource(pfad); return url; } }

pfad is the name of the File. For Example sbs.gif.

Sign up to request clarification or add additional context in comments.

3 Comments

I get a NullPointerException only if the File is not in the same Directory as the Locator class.
my images folder is outside of my src folder. i moved images into src folder. It's working now. But when it is in outside, it works for normal project running but not for jar running.
i have tried with that. but got same result. then i move it into src and then tried your code. it works for both. i thought images inside src is not good practice. Anyway it's working now. thanks a lot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.