[Java] Java常见读取*.properties文件的两种方法 →→→→→进入此内容的聊天室

来自 , 2020-04-14, 写在 Java, 查看 108 次.
URL http://www.code666.cn/view/450e92aa
  1. import java.io.InputStream;
  2. import java.util.Enumeration;
  3. import java.util.List;
  4. import java.util.Properties;
  5. import java.util.ResourceBundle;
  6.  
  7. import org.junit.Test;
  8.  
  9. /**
  10.  * 获取*.properties配置文件中的内容 ,常见的两种方法:
  11.  *
  12.  * @author 冰雨凌風
  13.  *
  14.  */
  15. public class ReadProperties {
  16.         // 方法一
  17.         @Test
  18.         public void One() {
  19.                 // 获得资源包
  20.                 ResourceBundle bundle = ResourceBundle.getBundle("test");
  21.                 // 通过资源包拿到所有的名称
  22.                 Enumeration<String> allName = bundle.getKeys();
  23.                 // 遍历
  24.                 while (allName.hasMoreElements()) {
  25.                         // 获取每一个名称
  26.                         String name = (String) allName.nextElement();
  27.                         // 利用已得到的名称通过资源包获得相应的值
  28.                         String value = bundle.getString(name);
  29.                         System.out.println(name + "=" + value);
  30.                 }
  31.         }
  32.  
  33.         // 方法二
  34.         @Test
  35.         public void Two() throws Exception {
  36.                 // 获得类加载器,然后把文件作为一个流获取
  37.                 InputStream in = ReadProperties.class.getClassLoader()
  38.                                 .getResourceAsStream("test.properties");
  39.                 // 创建Properties实例
  40.                 Properties prop = new Properties();
  41.                 // 将Properties和流关联
  42.                 prop.load(in);
  43.                 // 获取所有的名称
  44.                 Enumeration<?> allName = prop.propertyNames();
  45.                 // 遍历
  46.                 while (allName.hasMoreElements()) {
  47.                         // 获得每一个名称
  48.                         String name = (String) allName.nextElement();
  49.                         // 利用已得到的名称通过Properties对象获得相应的值
  50.                         String value = (String) prop.get(name);
  51.                         System.out.println(name + "=" + value);
  52.                 }
  53.                 // 关闭资源
  54.                 in.close();
  55.         }
  56. }
  57.  
  58. //java/6125

回复 "Java常见读取*.properties文件的两种方法"

这儿你可以回复上面这条便签

captcha