Java讀取Properties文件的七種方法的總結(jié)
Java讀取Properties文件的方法總結(jié)
讀取.properties配置文件在實際的開發(fā)中使用的很多,總結(jié)了一下,有以下幾種方法:
其實很多都是大同小異,概括起來就2種:
先構(gòu)造出一個InputStream來,然后調(diào)用Properties#load()
利用ResourceBundle,這個主要在做國際化的時候用的比較多。
例如:它能根據(jù)系統(tǒng)語言環(huán)境自動讀取下面三個properties文件中的一個:
- resource_en_US.properties
- resource_zh_CN.properties
- resource.properties
附上別人整理的6中方法...
1、使用java.util.Properties類的load()方法
InputStream in = new BufferedInputStream(new FileInputStream(name)); Properties p = new Properties(); p.load(in);
2、使用java.util.ResourceBundle類的getBundle()方法
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
3、使用java.util.PropertyResourceBundle類的構(gòu)造函數(shù)
InputStream in = new BufferedInputStream(new FileInputStream(name)); ResourceBundle rb = new PropertyResourceBundle(in);
4、使用class變量的getResourceAsStream()方法
InputStream in = JProperties.class.getResourceAsStream(name);//JProperties為當前類名 Properties p = new Properties(); p.load(in);
5、使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name); Properties p = new Properties(); p.load(in);
6、使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態(tài)方法
InputStream in = ClassLoader.getSystemResourceAsStream(name); Properties p = new Properties(); p.load(in);
7、在Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
InputStream in = context.getResourceAsStream(path); Properties p = new Properties(); p.load(in);
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Java實現(xiàn)世界上最快的排序算法Timsort的示例代碼
Timsort?是一個混合、穩(wěn)定的排序算法,簡單來說就是歸并排序和二分插入排序算法的混合體,號稱世界上最好的排序算法。本文將詳解Timsort算法是定義與實現(xiàn),需要的可以參考一下2022-07-07IntelliJ IDEA中Project與Module的概念以及區(qū)別
這篇文章主要給大家介紹了關(guān)于IntelliJ IDEA中Project與Module的概念以及區(qū)別的相關(guān)資料,文中通過實例介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01