java如何讀取property文件

最近在學習設計模式的時候,在練習動態配置的時候聯想到如果將所有的類型放在配置文件中那麼程序的靈活性和可擴展性會不會更好?
於是學習瞭如何讀取property文件的方法,並記錄下來方便自己和朋友。
下面是例子:
1、在同一個包下新建PropertiesTest 和fruit.properties文件

2、在fruit.properties中添加內容:
apple=com.meritit.porperties.PropertiesTest
words=老婆,我愛你

3、編寫測試類PropertiesTest 
public class PropertiesTest {

    /**
     * @param args
     * @throws UnsupportedEncodingException 
     */
    public static void main(String[] args) throws UnsupportedEncodingException {
        // TODO Auto-generated method stub
        Logger log= Logger.getLogger("log");
        log.setLevel(Level.INFO);//控制等級
        Properties pro = new Properties();
        InputStream inStream = PropertiesTest.class
                .getResourceAsStream("fruit.properties");
        try {
            pro.load(inStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info(pro.getProperty("apple"));
        String words =pro.getProperty("words");
        words = new String(words.getBytes("ISO-8859-1"),"UTF-8");//轉碼
        log.info(words);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章