开发者

How to Specify Path for Properties file

I am using Config. properties file for pas开发者_运维知识库sing parameters to my methods Now i am loading file from

Properties Config= new Properties(); Config.load(new FileInputStream("C:\\Config. properties "));

As i don't want to keep it hard coded how can i set it with package level. or within application.

Thanks in Advance.


Make use of ResourceBundle Class. You just need to specify the properties file name. It will take the file from any path,provided the path should be in the classpath.

Example:

// abc.properties is the properties file,which is placed in the class path.You just need to 
// specify its name and the properties file gets loaded.
ResourceBundle s=ResourceBundle.getBundle("abc");
        s.getString("key");   //any key from properties file...


I was also just going to suggest that but you can also pass in the full path to the config file via a command line argument for example:

java YourApp -config C:\\config.properties


A properties file packaged with the application should not be loaded using the file system, but using the class loader. Indeed, the properties file, once the application is packaged, will be embedded inside a jar file, with the .class files.

If the config.properties file is in the package com.foo.bar, then you should load it using

InputStream in = SomeClass.class.getResourceAsStream("/com/foo/bar/config.properties");

Or with

InputStream in = SomeClass.class.getClassLoader().getResourceAsStream("com/foo/bar/config.properties");

You may also load it with a relative path. If SomeClass is also in the package com.foo.bar, then you may load it with.

InputStream in = SomeClass.class.getResourceAsStream("config.properties");

Note that Java variables should always start with a lowercase letter: config and not Config.


If it's just the path you're worried about then you can use a relative path:

Config.load(new FileInputStream("Config.properties"));

This will look in the current working directory. The upsdie: dead simple. The downside: it's not that robust. If you start your application from somewhere else without changing the working directory before, the file won't be found.


Put the config file in the classpath (where your .class files are), and access it using

getClass().getClassLoader().getResourceAsStream(_path_to_config_file);


There are two ways to get the path of the config files at runtime.

a) Getting it from database. b) Getting it from custom properties of JVM configured at server level Best process is "b" , you can change the properties of JVM at any time if path is changed and just restart the server.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜