Properties类详解

来源:互联网 发布:房地产销售软件 编辑:程序博客网 时间:2024/06/06 02:58

该文主要介绍通过properties读取和存储properties文件和XML文件

1.properties文件操作

package cn;import java.io.*;import java.util.*;public class Other {public static void main(String[] args) throws Exception {Properties prop = new Properties();// 新建一个config.propertiesFile file = new File("config.properties");// 保存属性到config.properties文件FileWriter out = new FileWriter(file);// 设置键值prop.setProperty("键", "值");prop.setProperty("name", "zhangsan");// 将属性列表保存到输出流中/* * 如果comments不为空,保存后的属性文件第一行会是#comments,表示注释信息;如果为空则没有注释信息。 * 注释信息后面是属性文件的当前保存时间信息。 */prop.store(out, "Comment");out.close();// 读取属性文件config.propertiesFileReader in = new FileReader(file);/// 加载属性列表prop.load(in);// 获取指定内容String name = prop.getProperty("name");System.out.println("name:" + name);// 获取所有属性内容Iterator<String> it = prop.stringPropertyNames().iterator();while (it.hasNext()) {String key = it.next();System.out.println(key + ":" + prop.getProperty(key));}in.close();}}
1.1生成的config.properties

#Comment#Fri Dec 02 13:35:21 CST 2016键=值name=zhangsan
2.XML文件操作

package cn;import java.io.*;import java.util.*;public class Other {public static void main(String[] args) throws Exception {Properties prop = new Properties();// 新建一个config.propertiesFile file = new File("config.xml");// 保存属性到config.xml文件FileOutputStream out = new FileOutputStream(file);// 设置键值prop.setProperty("键", "值");prop.setProperty("name", "zhangsan");// 将属性列表保存到输出流中/* * 如果comments不为空,保存后的属性文件第一行会是#comments,表示注释信息;如果为空则没有注释信息。 * 注释信息后面是属性文件的当前保存时间信息。 */prop.storeToXML(out, "Comment");out.close();// 读取属性文件config.xmlFileInputStream in = new FileInputStream(file);/// 加载属性列表prop.loadFromXML(in);// 获取指定内容String name = prop.getProperty("name");System.out.println("name:" + name);// 获取所有属性内容Iterator<String> it = prop.stringPropertyNames().iterator();while (it.hasNext()) {String key = it.next();System.out.println(key + ":" + prop.getProperty(key));}in.close();}}
2.1生成的config.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"><properties><comment>Comment</comment><entry key="键">值1</entry><entry key="name">zhangsan</entry></properties>

通过properties读取该xml有着严格的约束,不能自己创建或添加节点

0 0
原创粉丝点击