简体   繁体   中英

Loading image from a Java file

I have this project structure:

  • ProjectName
    • src
      • xxx
        • co
          • com
            • package
              • something.java
    • web
      • image
        • print
          • pic.jpg
I want to load the pic.jpg in the java file which will then be used in the pdf file generated. I have gone through the answers here but, nothing helped me yet. Possibly I am missing a small thing.

If the pic.jpg was under package, then getClass().getResource("pic.jpg") works absolutely fine. getClass().getResource("/web/image/print/pic.jpg") doesnt work as well. But I want to place all my images under image folder and refer it in the java file.

You should get the application runtime path and rebase the path to the folder which images locate.
You can use the code:

String path = new File(".").getCanonicalPath();// or System.getProperty("user.dir")

Seems your files are not copied to bin/ directory. Change your build script to copy them to output directory

getClass().getResource() will use class loader to load class, since those files need to be in classpath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM