Java读取配置文件

一、通过jdk提供的java.util.Properties类
  此类继承自java.util.HashTable,即实现了Map接口,所以,可使用相应的方法来操作属性文件,但不建议使用像put、putAll这两个方法,因为put方法不仅允许存入String类型的value,还可以存入Object类型的。因此java.util.Properties类提 供了getProperty()和setProperty()方法来操作属性文件,同时使用store或save(已过时)来保存属性值(把属性值写 入.properties配置文件)。在使用之前,需要加载属性文件,它提供了两个方法:load和loadFromXML。

load有两个方法的重载:load(InputStream inStream)、load(Reader reader),可根据不同的方式来加载属性文件。

读取prperties文件方式:

Properties date = new Properties();
InputStream input = new FileInputStream("src/config/date.properties");
date.load(input);		
String str = date.getProperty("china");
input.close();

写入prperties文件方式:

Properties date = new Properties();
OutputStream output = new FileOutputStream("src/config/date.properties");
date.setProperty("china", "中文");
date.store(output, "author:sky");
output.close();

 读取xml文件方式: 

Properties date = new Properties();
InputStream input = new FileInputStream("src/config/date.xml");
date.loadFromXML(input);
System.out.println(date.getProperty("username"));
input.close();


写入xml文件方式:

Properties date = new Properties();
OutputStream output = new FileOutputStream("src/config/date.properties");
date.setProperty("china", "中文");
date.storeToXml(output, "author:sky");
output.close();

xml文件,格式如下:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<entry key="password">mypassword</entry>
	<entry key="chinese">中文</entry>
	<entry key="username">myname</entry>
</properties>

Properties  不仅可以读写上述两类文件,还可以读写其它格式文件如txt等,只要符合key=value格式即可。

二、通过java.util.ResourceBundle类来读取properties文件
1、通过ResourceBundle.getBundle()静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名(必须不加),只需要文件名即可。

ResourceBundle resource = ResourceBundle.getBundle("config/date");
System.out.println(resource.getString("china"));

2、从InputStream或Reader中读取

InputStream input = new FileInputStream("src/config/date.properties");
ResourceBundle resource = new PropertyResourceBundle(input);
System.out.println(resource.getString("smile"));


注意:属性文件在src根目录下,ResourceBundle.getBundle("filepath")直接写文件名即可即:date,其他需写全路径

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值