Loading the configuration file from the class path

I am working on making my Java application easy to deploy to other computers, and I am writing an ant script to do this. This is normal.

I am having problems loading the resources listed in the class path specified in the jar manifest file.

The folder structure is as follows:

/MyProgram.jar /lib/<dependencies> /config/configuration.xml 

I can’t access my configuration.xml file with ClassLoader for life. It, together with all the dependencies, is explicitly specified in the Class-Path entry in the manifest file.

I tried many options:

 this.xml = Thread.currentThread().getContextClassLoader() .getResourceAsStream(xmlName); this.xml = this.getClass().getResourceAsStream(xmlName); 

With xmlName as a string of all of the following values:

 "config/configuration.xml" "configuration.xml" "config.configuration.xml" 

For this reason, I also have a log4j.properties file in the config directory. How can i get log4j? Other links say that it just needs to be in the classpath, and it is also explicitly specified in the jar manifest file. Can someone point me in the right direction?

Update:

Here are the actual entries from Class-Path:

 Class-Path: <snip dependencies> config/configuration.xml config/log4j.properties 
+4
source share
4 answers

Pathpath elements must be either directories or jar files, not separate files. Try changing the class path to point to the configuration directory instead of the individual configuration files.

 this.xml = Thread.currentThread().getContextClassLoader() .getResourceAsStream("config.xml"); 

It is best to simply include your config directory in MyProgram.jar. This would prevent you from adding it specifically to the classpath.

 this.xml = Thread.currentThread().getContextClassLoader() .getResourceAsStream("/config/configuration.xml"); 
+13
source

As far as I know, log4j.xml should be at the root of your classpath.

and also you can read your configuration file with the code below the script. and the config directory should be in your classpath.

 this.xml = this.getClass().getResourceAsStream("/config/configuration.xml"); 
+3
source

When starting the application, you can use the system property log4j.configuration :

 java -Dlog4j.configuration=config/log4j.properties MyApp 

See http://logging.apache.org/log4j/1.2/manual.html in the Default Initialization Procedure section.

As for other configuration files that are not collected, what does your Manifest.mf file look like? You use something like

 Class-Path: config/configuration.xml lib/yourLibOne.jar lib/blah.jar 

in your Manifest.mf file?

+1
source

Regarding log4j: if you want it to use a different default configuration file, you can use

 org.apache.log4j.PropertyConfigurator.configure(...) 

Variants of this static method accept a URL, Properties, or file name.

There is also

 org.apache.log4j.xml.DOMConfigurator 

for XML files.

0
source

Source: https://habr.com/ru/post/1337383/


All Articles