java通過相對路徑讀取properties資料

shuaishuai3409發表於2017-01-13

主要是通過getResourceAsStream方法來實現相對路徑的讀取,相對路徑的意思就是以專案所在路徑為基準,讓程式知道其在專案的哪個路徑下面。

public class ReadProperties {
    private static ReadProperties instance;
    private static Properties prop;
    private ReadProperties (){} 

    /*public static ReadProperties getInstance() {
        if (instance == null) {  
            instance = new ReadProperties();  
        }
        return instance;  
        } */

    public static  Properties readProp(){
        if(prop==null){
            prop=new Properties();
            try{

                prop.load(ReadProperties.class.getResourceAsStream("/hbase.properties"));
                Enumeration<String> en = (Enumeration<String>)prop.propertyNames();
                while(en.hasMoreElements()){
                    String confkey = en.nextElement();
                    String value = prop.getProperty(confkey);
                    System.out.println("key:"+confkey+","+"value:"+value);
                }
                 }catch(Exception e){
                    e.printStackTrace();
                 }
        }
        return prop;
    }

}
hbase.properties的內容:

tableName =helloHbase
public static void main(String[] agrs)
    {

        String tablename =ReadProperties.readProp().getProperty("tableName");
        System.out.println(tablename);

    }

相關文章