Properties类
该类是位于util包里的一个工具类,与IO的结合能十分有效的读写文件,特别在准确快速读取方面效率十分高,另外该类结合了util里面的HashMap的存储方法,使用了键值对的方式进行存储。
//创建一个Properties对象
Properties()
Properties类的常用方法
//通过字符流加载一个文件
void load(Reader reader)
//通过字节流加载一个文件
void load(InputStream in)
//通过键值获取文件中对应的value值
String getProperty(String key)
//存入一个键值对
Object setProperty(String key,String value)
//以适合使用load方法加载到Properties表中的格式,将此Properties表中的属性列表(键和元素对)写入输出流
void store(OutputStream out, String comments)
下面通过一个案例来深入体会Properties类的用法:
案例:向位于D盘的liaozhongmin.properties文件写入两对值,然后在遍历出这个文件中的内容
public class PropertiesTest {
public static void main(String[] args) {
//向属性文件写入数据
//创建Properties对象
Properties properties = new Properties();
//创建字节输出流用于写文件
OutputStream os = null;
try {
os = new FileOutputStream("D:\\liaozhongmin.properties");
properties.setProperty("uid", "2");
properties.setProperty("name", "lavimer");
properties.setProperty("gender", "男");
properties.store(os, " 创建时间:"+ new Date());
} catch (Exception e) {
e.printStackTrace();
}
/从属性文件中读取数据//
try {
//创建输入流用于读取属性文件
InputStream inputStream = new FileInputStream("D:\\liaozhongmin.properties");
properties.load(inputStream);
//获取文件的所有属性
Enumeration<String> enums = (Enumeration<String>) properties.propertyNames();
//遍历枚举类型
while (enums.hasMoreElements()){
//获取key值
String key = enums.nextElement();
//通过key值获取value值
String value = properties.getProperty(key);
//输出
System.out.println(key + " ==> " + value);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}