How to load Properties file from a static block or static method

来源:互联网 发布:淘宝客服售前售后要点 编辑:程序博客网 时间:2024/06/05 14:25

通常,通用类会从静态上下文读取属性文件,这下面是一个例子

mport java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class MyPropInStaticBlock {
 
    private static Properties prop;
     
    static{
        InputStream is = null;
        try {
            prop = new Properties();
            is = ClassLoader.class.getResourceAsStream("/sample.properties");
            prop.load(is);
        catch (FileNotFoundException e) {
            e.printStackTrace();
        catch (IOException e) {
            e.printStackTrace();
        }
    }
     
    public static String getPropertyValue(String key){
        return prop.getProperty(key);
    }
     
    public static void main(String a[]){
         
        System.out.println("db.host: "+getPropertyValue("db.host"));
        System.out.println("db.user: "+getPropertyValue("db.user"));
        System.out.println("db.password: "+getPropertyValue("db.password"));
    }
}

sample.properties

?
1
2
3
4
db.host=appdomain.java2novice.com
db.user=java2novice
db.password=mypassword
db.service=orcl

Output:
db.host: appdomain.java2novice.comdb.user: java2novicedb.password: mypassword

0 0
原创粉丝点击