一、通过jdk提供的java.util.Properties类
此类继承自java.util.HashTable,即实现了Map接口,所以,可使用相应的方法来操作属性文件,但不建议使用像put、putAll这两个方法,因为put方法不仅允许存入String类型的value,还可以存入Object类型的。因此java.util.Properties类提 供了getProperty()和setProperty()方法来操作属性文件,同时使用store或save(已过时)来保存属性值(把属性值写 入.properties配置文件)。在使用之前,需要加载属性文件,它提供了两个方法:load和loadFromXML。
写入prperties文件方式:
xml文件,格式如下:
2、从InputStream或Reader中读取
此类继承自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();
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,其他需写全路径