Search code examples
javaresourcessubdirectory

How to specify the path correctly to open a file from a sub directory of my project?


I have my project structure like this

--src

--------------resources

--------------saves

I use this subfolder at multiples times like this:

 File tempFile = new File("src/saves/" + videoName + ".json");

or sometimes like this :

ImageView icon = new ImageView("resources/edit.png");

and :

File f = new File("src/resources/zelda.mp4");

For some reasons it works for the icon but not for the video/file, when I try I get this error:

Caused by: MediaException: MEDIA_UNAVAILABLE : C:\Users\histackoverflow\IdeaProjects\project2\resources\zelda.mp4 (specified path can't be found)

so I want to know what is wrong in my way of using path ?


Solution

  • @Edit: this works fine for referencing files in IDE. For appropriate file references in jar, follow this: Java Jar file: use resource errors: URI is not hierarchical

    I wouldn't recommend typing in the path as a String. A better way of loading files is placing them into recources (you already did that) and call the rescource by class reference and getting URI from it:

        InputStream file = new FileInputStream(getClass().getResource("/edit.png").getPath());
        Image image = new Image(file);
        ImageView icon = new ImageView(image);
    
    
        File f = new File(getClass().getResource("/zelda.mp4").toURI());
    

    Make sure, that your directory with resources is marked as a resource directory.