java讀取配置文件常用的四種方式

配置文件
放置在src下面 obj.properties

className=com.store.order.dao.impl.OrderDaoImpl


方式一

@Test
    public void test1() throws Exception{
        //文件放在src下面.eclipse會自動拷貝一份到bin目錄下,或者build/classes下面,
        InputStream is = Class.forName("com.store.test.test").getClassLoader().getResourceAsStream("obj.properties");
        Properties properties = new Properties();
        properties.load(is);
        String className = properties.getProperty("className");
        System.out.println(className);
    }

方式二

    /**
     * 不推薦使用,文件位置被固定了,只能在本機使用,我們把class文件拷貝給別人就不能使用了
     * @throws Exception
     */
    @Test
    public void test2() throws Exception{
        FileInputStream fis = new FileInputStream("D:\\workspaces\\store_v1.0\\src\\obj.properties");
        Properties properties = new Properties();
        properties.load(fis);
        String className = properties.getProperty("className");
        System.out.println(className);
    }

方式三

    @Test
    public void test3() throws Exception{
        //讀取配置文件,只能讀取默認後綴名爲properties(不寫)
        //如果有包,寫法是com.store.obj
        //細節:他只能讀取類路路徑下的文件,不能寫入
        ResourceBundle bundle = ResourceBundle.getBundle("obj"); 
        String className = bundle.getString("className"); //通過鍵獲取值
        System.out.println(className);
    }

方式四

/** 
 * Spring 提供的 PropertiesLoaderUtils 允許您直接通過基於類路徑的文件地址加載屬性資源 
 * 最大的好處就是:實時加載配置文件,修改後立即生效,不必重啓 
 */  
private static void springUtil(){  
    Properties props = new Properties();  
    while(true){  
        try {  
            props=PropertiesLoaderUtils.loadAllProperties("message.properties");  
            for(Object key:props.keySet()){  
                System.out.print(key+":");  
                System.out.println(props.get(key));  
            }  
        } catch (IOException e) {  
            System.out.println(e.getMessage());  
        }  

        try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}  
    }  
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章