简体   繁体   中英

Read config file from classpath in Java with default in JAR

UPDATE: As it turns out in some of the tests I was conducting the classpath was not being set correctly in the IDE. The snippet below works properly. This is no longer an issue.

I'm trying to set some properties/configurations in a text file that will be deployed inside a JAR.

I want the users to be able to supply their own properties/configurations file which will override the one used in the JAR, so the one in the JAR will only be used if the user-supplied file does not exist.

I am using Class.getResource(path), which should be able to find both relative and absolute (with a leading slash) files.

given the following file hierarchy inside the JAR:

<jar-file>/SomeClass.class
<jar-file>/conf/config-file.txt

and an optional file at

<some-classpath-folder>/conf/config-file.txt

I am trying to do something like the snippet below, so that only if the file is not found in an absolute folder conf from the classpath, it will be loaded from the relative conf folder inside the JAR:

Class clasz = SomeClass.class;
res = clasz.getResource("/conf/config-file.txt");    // absolute file not found, note leading-slash

if (res == null)
    res = clasz.getResource("conf/config-file.txt"); // relative file is found, No leading-slash

The relative file (from within the JAR) is found, but the absolute one from the classpath is not.

Calling System.getProperty("java.class.path") shows the <some-classpath-folder> folder, so it looks like the classpath is set correctly, and yet the file at <some-classpath-folder>/conf/config-file.txt is not found.

Is there a way to know which folders were scanned in search of the file? Or any suggestions on what's going wrong here?

TIA

If you rely solely on classpath resources you are at the mercy of the classpath hierarchy, how the program is run, etc. This may work, but it's not entirely within your control.

IMO it would be better to check for an explicitly-defined path, eg, via a system property like -Dconfig=/path/to/config , a known location like a file in the user's home, or the properties API.

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