Java读取Properties文件[基础读取方式]

本文详细介绍了如何通过Java语言从properties文件中读取属性值,并对比了使用InputStream与ResourceBundle两种方式获取数据时的输出顺序区别。重点在于理解并解决在读取配置文件时可能遇到的顺序不一致问题。
[url]http://my.oschina.net/plumsoft/blog/66225[/url]
有一个properties文件box.properties,内容如下:

Color=Red
Name=Box
Length=18
Width=7
Heigth=8

获取其中的属性值,可用如下代码:

InputStream in = null;
Properties p = new Properties();
try {
in = new BufferedInputStream(new FileInputStream("box.properties"));
p.load(in);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Enumeration<Object> keys = p.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
System.out.println(key + ":" + p.getProperty(key));
}

或者:

InputStream in;
ResourceBundle rb = null;
try {
in = new BufferedInputStream(new FileInputStream("box.properties"));
rb = new PropertyResourceBundle(in);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (rb != null) {
Enumeration<String> keys = rb.getKeys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
System.out.println(key + ":" + rb.getString(key));
}
}

不过输出顺序与原始文件不同。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值