Properties操作配置文件
此类用于操作系统的配置文件: ini(.properties)形式的配置,xml格式的配置文件
/**
* properties操作配置文件
*
* @author xiazhang
* @date 2017-6-4
*/
public class PropertiesTest {
/**
* 生成配置文件
*/
public static void createIniFile(){
//新建一个properties对象
Properties p = new Properties();
p.put("name", "xiazhang");
p.put("sex", "男");
/*
try {
FileOutputStream fos = new FileOutputStream("memberInfo.properties");
//保存为配置文件
p.store(fos, "commnet");
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
FileOutputStream fos = new FileOutputStream("memberInfo.xml");
//使用xml作为配置文件
p.storeToXML(fos, "comment");
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 读取配置文件
*/
public static void readIniFile(){
Properties p = new Properties();
try {
FileInputStream fis = new FileInputStream("memberInfo.properties");
//加载配置文件
p.load(fis);
//System.out.println(p.get("name"));//直接根据key获取值
//遍历输出
//线程安全遍历发 //迭代遍历器Enumeration
Enumeration en = p.elements();
while (en.hasMoreElements()) {
System.out.println(en.nextElement());
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
//createIniFile();
readIniFile();
}
}