0

Hey is it possible to get an image from file without using the full file location in java? My code below will only work with the full file path:

Icon icon = new ImageIcon("/Users/MyMac/Documents/Project/Software/Project/src/UI/Images/default_pic.png");

Is it possible to use the file path as such?:

Icon icon = new ImageIcon("/src/UI/Images/default_pic.png");
3
  • 2
    Try removing the first /. Commented Feb 24, 2013 at 15:09
  • You would have to set the CLASSPATH appropriately. Commented Feb 24, 2013 at 15:10
  • 1
    thank you for the helpful comment as opposed to a negative like others Commented Feb 24, 2013 at 15:11

1 Answer 1

2

"/src/UI/Images/default_pic.png" is an absolute path, so it will look for a src directory in the root directory, then a UI subdirectory in it, etc. Not what you want.

You can use a relative path such as "src/UI/Images/default_pic.png" (notice it doesn't start with a "/"), but as its name says, it is relative to the current directory. So it will work if your current directory is /Users/MyMac/Documents/Project/Software/Project (or any directory that contains the file in the same subpath), otherwise it won't.

Finally, another way is to access the file through the classpath. Considering that the project could be packed in a jar file, the image file might not be a separate file on the disk, but you can still get a URL or InputStream to access it. Search for getResource and getResourceAsStream in Class and ClassLoader.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.