简体   繁体   中英

How to Specify Path for Properties file

I am using Config. properties file for passing 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...

我也只是建议,但您也可以通过命令行参数将完整路径传递到配置文件,例如:

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 .

将配置文件放在类路径(您的.class文件所在的位置)中,并使用

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.

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.

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