I am attempting to make a simple menu in JavaFX. When I attempt to load an image using a relative path I receive the following exception:
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1110)
I am using eclipse, although this problem appears not be eclipse specific, since I have received the same exception when running in terminal. Also, for some reason it works when the file is in inside the package or in the src folder (given path is changed appropriately).
My Current active class Menu.java
is in the package test.dsp
, which is located in the project as:
project/src/test/dsp/Menu.java
The file I am attempting to access:
project/assets/graphics/test/dsp/sslogo.png
I am attempting to access the file under the assumption that this path is relative to the current Menu
class in Menu.java
and due to the physical directories being project/src/test/dsp/Menu.java
, I am implementing ../
thrice in my relative path to get to the project directory. Then I simply put the path to the image as seen below.
Image ssLogo = new Image("../../../assets/graphics/test/dsp/sslogo.png",
2000, 2000, true, true);
I am basing my knowledge off of the constructor described in the JavaFX API:
public Image(java.lang.String url,
double requestedWidth,
double requestedHeight,
boolean preserveRatio,
boolean smooth)
url - the string representing the URL to use in fetching the pixel data
I have searched through a plethora of questions but their answers do not provide a solution to making my current case work. I've tried getResource, getResourceAsStream, and external resource. I checked the URL that is returned by these means and none worked with my provided path as seen above. I also tried different numbers of ../
, still to no avail. Admittedly, I may have implemented them wrong, which led to no success.
Why does this method of file access via relative path not work and how can I make this work with my current directory set up?
What is the proper way to access a file via a relative path in java in general? And specifically when the file is outside of the package, such as this case?
- is there a way to include the file into the file path via code in the java class?
Is it more efficient to have the file inside the package, or does it not matter (clearly depending on the means of accessing the file outside of package)?
- is there a more effective means of file access through java?