开发者

Find conf file regardless how application started

开发者 https://www.devze.com 2023-03-08 09:58 出处:网络
I\'m newbie to java. I have some directory structure product/ conf/ classes/com/../.. conf/ contains some configuration file, while under classes/ I have my application.

I'm newbie to java.

I have some directory structure

  product/
        conf/
        classes/com/../.. 

conf/ contains some configuration file, while under classes/ I have my application.

How can I ensure from inside java code that I'm able to find file in conf/ despite way I'm executing it (e.g. from eclipse, from different directories, from crontab etc.).

P.S.

Files in conf/ are not resources, since required to be edited by user. Is there're way to know where my .class, so I canuse relative path form 开发者_如何学JAVAthat directory to reach my directory (e.g. MY_CLASS_DIR/../../../../conf)


I would put the conf directory into the class path. That way you can always find them by:

YourClass.class.getClassLoader().getResource("conf/....");


You can use the absolute path, including the way to product.

Or you may use a configuration setting, by starting your program like

java -DXY_HOME=/some/path/product ...

From the javacode, you use it:

String xyHome = System.getProperty ("XY_HOME") 

Or you use a kind of inifile in your home directory, where you specify where to look for the conf-directory.

Rereading your question multiple times, it is unclear to me what your goal is. To find the conf dir independently from where you are (eclipse, crontab, ...)? But the headline asks for the CWD, which is the opposite - the directory, depending on where you are.

Both is possible, but you have to decide what you want.


Its safe to use relative paths than absolute paths. Even if you JAR your classes tomorrow it will work as is,

Put you configuration files in classpath during deployment.(Please note that project directory structure can be different from that of deployment directory structure)

product/       
    classes/com/../..
    classes/conf/some_conf.properties

Then you can use Apache common configuration to get the URL of file

URL urlOfFile = org.apache.commons.configuration.
ConfigurationUtils.locate("conf/some_conf.properties");

The other alternative you can try is,

URL urlOfFile = <SomeClassFromClassesFolder>.class.
getClassLoader().getResource(resourceFile);

Once you get the URL of your configuration file getting stream out of it very simple,

InputStream stream = urlOfFile.openStream();

Good luck.

For you understanding you can refer the following as well,

http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_IO_CurrentWorkingDirectory

http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_Reflection_WheretheClassloadedfrom Good luck.


you can find out what is the absolute path of the working dir by:

String str = new File("").getAbsolutePath()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号