Is there a universal format / method for finding configuration files on Windows and Linux?

In my application, I have a configuration file (ABC.xml) in which we have the database attributes, the path log4j.xml and others. The log4j.xml path is specified in ABC.xml as ( D:\log4j.xml ) and for linux as ( .\\..\\..\\log4j.xml\\ ).

We use the apache tomcat server, and we have ABC.xml in the server context.

Is there any way for me to have the same path representation for log4j for both windows and linux, but it will be interpreted accordingly depending on the type of server?

+4
source share
3 answers

Well, if you use a servlet and the file is in the project, inside the servlet you can simply:

 InputStream is = getServletContext().getResourceAsStream("/log4j.xml"); 
+1
source

Processing java files can work with / like seperator on Windows operating systems, so you can write in your ABC.xml ./../../log4j.xml for linux and windows (the path should be relative and should not contain a disk letter) .

So when you write in your code

 File f = new File("./../../log4j.xml"); 

the argument "./../../log4j.xml" for internal windows will be translated into ".\\..\\..\\log4j.xml" and

 f.getAbsolutePath(); 

will return in windows the string "C:\\some\\dir\\.\\..\\..\\log4j.xml" witch prints as C:\some\dir\.\..\..\log4j.xml , where C:\some\dir is the directory in which witch .\..\..\log4j.xml refers to.

+1
source

A general approach is to use paths relative to the system property. This allows you to specify the root folder in a specific OS format ( C:\... or /opt/ ) and attach the relative part later.

Please note that Java can handle relative Windows and Unix paths, so new File( "C:\\app", "conf/log4j.xml" ) will try to open C:\app\conf\log4j.xml .

In your case, you can use this code:

 File confFolder = new File( System.getProperty( "confDir" ) ); File log4j = new File( confFolder, "log4j.xml" ); 

Another option is to replace the variable names in the configuration files. So you can have

 <logConfDir>${appRoot}/conf</logConfDir> <log4j>${logConfDir}/log4j.xml</log4j> 

If there is a System logConfDir property, it should overwrite the configuration parameter. This will allow customers to do whatever they think is necessary.

+1
source

All Articles