Java 獲取*.properties配置文件中的內容 ,常見的兩種方法
import java.io.InputStream; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.ResourceBundle;import org.junit.Test;
/**
- 獲取*.properties配置文件中的內容 ,常見的兩種方法:
- @author 冰雨凌風
*/ public class ReadProperties { // 方法一 @Test public void One() {
// 獲得資源包 ResourceBundle bundle = ResourceBundle.getBundle("test"); // 通過資源包拿到所有的名稱 Enumeration<String> allName = bundle.getKeys(); // 遍歷 while (allName.hasMoreElements()) { // 獲取每一個名稱 String name = (String) allName.nextElement(); // 利用已得到的名稱通過資源包獲得相應的值 String value = bundle.getString(name); System.out.println(name + "=" + value); }}
// 方法二 @Test public void Two() throws Exception {
// 獲得類加載器,然后把文件作為一個流獲取 InputStream in = ReadProperties.class.getClassLoader() .getResourceAsStream("test.properties"); // 創建Properties實例 Properties prop = new Properties(); // 將Properties和流關聯 prop.load(in); // 獲取所有的名稱 Enumeration<?> allName = prop.propertyNames(); // 遍歷 while (allName.hasMoreElements()) { // 獲得每一個名稱 String name = (String) allName.nextElement(); // 利用已得到的名稱通過Properties對象獲得相應的值 String value = (String) prop.get(name); System.out.println(name + "=" + value); } // 關閉資源 in.close();} } </pre>
本文由用戶 javapp 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!