简体   繁体   English

如何设置CLASSPATH来加载相对于jar文件的资源?

[英]How to setup the CLASSPATH to load resources relative to the jar file?

I have some jar files that need to read files at startup. 我有一些jar文件,需要在启动时读取文件。 These files are located in directories next the jar files. 这些文件位于jar文件旁边的目录中。 This is how my directory listing looks like: 这是我的目录清单的样子:

code.jar
config/
       confifile.cfg

Then, in a command line prompt, I set the classpath as: 然后,在命令行提示符下,将类路径设置为:

set CLASSPATH=./ext/*;./*

Then I run the program but it keeps complaining that it cannot find the "configfile.cfg". 然后,我运行该程序,但始终抱怨找不到“ configfile.cfg”。

/config/configfile.cfg file not found! 找不到/config/configfile.cfg文件!

This error comes from this code: 此错误来自以下代码:

try {
    r = new BufferedReader(new FileReader((String)botinfilename));
    fileName=(String)botinfilename;
}
catch (FileNotFoundException e) {
    System.err.println(botinfilename + " is not found");
}

I noticed it works if I put the /config directory inside the jar file. 我注意到,如果我将/ config目录放在jar文件中,它会起作用。 But if I remove it and put it next to the jar it does not find the config file. 但是,如果我将其删除并将其放在jar旁边,则找不到配置文件。

Is there some java setting trick to make this work? 有一些Java设置技巧可以使这项工作吗?

EDIT 1: 编辑1:

I launch my program like this: 我这样启动程序:

java StartProgram java StartProgram

To keep it short, I just added the "-cp" JVM option. 为了简短起见,我刚刚添加了“ -cp” JVM选项。 My problem was I need to add the root directory (where my jars and resources are located) to my classpath. 我的问题是我需要将根目录(我的jar和资源所在的位置)添加到我的类路径中。 Previously I had just added the jars with the * wildcard. 以前,我刚刚在罐子中添加了*通配符。

java -cp PATH_ROOT_DIR/;PATH_TO_ROOT_DIR/*;PATH_TO_ROOT_DIR/ext/* StartProgram

or you can set the class path 或者您可以设置课程路径

set CLASSPATH=./;./ext/*;./*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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