简体   繁体   中英

Can't locate resource file in JAR

I have a class in my Java application, which reads a resource folder which is located in src/main/resources . So, in that class, I am specifying the resource folder as:

public static final String RES_LOCATION = "./src/main/resources";

The program runs fine. But when I make a jar and use that as a dependency in another project, that above class fails as it cannot find the resource folder.

Any solution?

您需要从该目录中读取特定文件作为类路径资源而不是java.io.File

getClass().getResourceAsStream("relative/class/path/to/resource");

您指定了错误的资源路径,您需要加载资源,如资源'public static final String RES_LOCATION =“resources”',因为src / main将不存在。

./src/main/resources is related to the structure of your project and is not the same when you package your code to .jar file. Both structures are very different and it can affect the way you access your file.

The best practice to access a file in a resource can be found on this page : https://www.mkyong.com/java/java-read-a-file-from-resources-folder/

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