Java: Loading resources from the file system

后端 未结 5 408
臣服心动
臣服心动 2021-01-22 18:07

My Project Setup

I have the following project setup:

\\program.jar  
\\images\\logo.png

In my code, I reference th

相关标签:
5条回答
  • 2021-01-22 18:20

    As Nelson mentioned, package them with your JAR (just copy them alongside your .class files), then you can find them via a simple this.getClass().getClassLoder().getResource("images/foo.png").

    0 讨论(0)
  • 2021-01-22 18:21

    Resources have to be in the class path(s). You may try one of these:

    1. Placing the images into the program.jar.
    2. Like most of the programs, they have a APP_HOME directory, e.g. MAVEN_HOME, register that and refer to your files as File instead - $APP_HOME/the-file.ext (with System.getenv()).
    0 讨论(0)
  • 2021-01-22 18:25

    You should really include your resources in your JAR.

    Failing that, you can parse the absolute path out of the Main class resource. Assuming your Main class is actually called "Main":

    Main.class.getResource("Main.class").getPath();
    
    0 讨论(0)
  • 2021-01-22 18:34

    What I would do, if possible, is package your images in with your Jar.

    That way you don't have to worry about where your Jar is launched from.

    You would then need to load images similar to the following:

    InputStream stream = this.getClass().getClassLoader().
                                         getResourceAsStream("/images/logo.png");
    
    0 讨论(0)
  • 2021-01-22 18:37

    You need to add a parameter which describes your class path. Should look something like

    java -cp c:\projects\program_dir\bin -jar program.jar
    

    this will put your jar and image on the class path and it will load successfully.

    0 讨论(0)
提交回复
热议问题