Java 获取*.properties配置文件中的内容 ,常见的两种方法
发布时间:2020-05-24 22:04:22 所属栏目:Java 来源:互联网
导读:Java 获取*.properties配置文件中的内容 ,常见的两种方法
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 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();
}
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
