java Properties配置文件写入与读取

来源:互联网 发布:动漫设计软件手机软件 编辑:程序博客网 时间:2024/06/09 22:53

一、Properties

1.作用:读写资源配置文件;

2.键与值只能为字符串;

3.方法:

setProperty(String key,String value)

getProperty(String key)

getProperty(String key,defaultValue)


后缀:.Properties

store(OutputStream out,String comments)

store(Wirter wirter,String comments)

.xml

storeToXML(OutputStream os,String comment);

storeToXML(OutputStream os,String comment,String encoding);

存储例子:

package com.uwo9.test05;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;public class Test01 {public static void main(String[] args) throws FileNotFoundException, IOException {Properties pro = new Properties();// 存储pro.setProperty("driver", "oracle.jdbc.dirver.OracleDriver");pro.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl");pro.setProperty("user", "scott");pro.setProperty("pwd", "tiger");// 获取// String url1=pro.getProperty("url1", "test");//存在获取给定值,不存在获取默认值// System.out.println(url1);// 存储到e:others绝对路径 盘符:// pro.store(new FileOutputStream("e:/others/db.properties"), "db配置");// pro.storeToXML(new FileOutputStream("e:/others/db.xml"), "db配置");// 使用相对路径 当前工程pro.store(new FileOutputStream("db.properties"), "db配置");}}

读取例子:

package com.uwo9.test05;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Properties;public class Test01 {public static void main(String[] args) throws FileNotFoundException, IOException {Properties pro = new Properties();// 读取绝对路径// pro.load(new FileReader("e:/others/db.properties"));// 读取相对路径//pro.load(new FileReader("src/com/uwo9/others/pro/db.properties"));// 类相对路径 /bin    bin目录下读取//pro.load(Test01.class.getResourceAsStream("/com/uwo9/others/pro/db.properties"));// "" bin//pro.load(Test01.class.getClassLoader().getResourceAsStream("com/uwo9/others/pro/db.properties"));pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/uwo9/others/pro/db.properties"));System.out.println(pro.setProperty("user", "test"));}}