Java读取properties文件举例

本文介绍了在Java中读取Properties配置文件的五种常见方式,包括使用FileInputStream、Class.getResourceAsStream、ResourceBundle、Class.getClassLoader及ClassLoader.getSystemResourceAsStream等方法,并提供了具体的代码示例。

Java读取Preperties的文件方式有很多,这里只列了5种,举例如下:

方式一:

1
2
3
Properties property =newProperties();
property.load(newFileInputStream("你的文件位置"));//需要指定文件具体位置,如果是web项目,则要指定要WEB-INF/classes下
String value = property.getProperty("你的属性的key");

方式二:

1
2
3
4
5
Properties prop =null;
InputStream is;
prop =newProperties();
is = Constants.class.getResourceAsStream("/test.properties");// 需要加/
prop.load(is);

方式三:

1
2
3
4
ResourceBundle rb = ResourceBundle.getBundle("test", Locale.getDefault());
String s = rb.getString("PATH");
不加/,也不加 .properties,

用ResourceBundle读取.properties文件可避免路径问题

方式四:

1
2
3
4
5
6
Properties prop =null;
InputStream is;
prop =newProperties();
is = Constants.class.getClassLoader().getResourceAsStream("test.properties");// 不需要加/
prop.load(is);
returnprop.getProperty("PATH");

方式五:

1
2
3
InputStream in = ClassLoader.getSystemResourceAsStream("test.properties");
Properties p =newProperties();
p.load(in);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值