java.util.Properties用法

来源:互联网 发布:mac vi命令保存退出 编辑:程序博客网 时间:2024/06/05 17:32

java.util.Properties是对properties这类配置文件的映射。支持key-value类型和xml类型两种。

key-value类型的配置文件大略长这样:

#测试环境配置:平台路径配置jstrd_home=D:/TMS2006/webapp/tms2006/WEB-INF/dbPort = localhostdatabaseName = myddbUserName = root

#打头的是注释行,Properties会忽略注释。允许只有key没有value。

例如这样:

#测试环境配置:平台路径配置jstrd_home=D:/TMS2006/webapp/tms2006/WEB-INF/dbPort = databaseName

这种情况下,value会被set成null。

properties类实现了Map接口,所以很明显,他是用map来存储key-value数据,所以也注定存入数据是无序的,这个点需要注意。只能通过key的方式来get对应value。

针对key-value这种配置文件,是用load方法就能直接映射成map,非常简单好用。这种配置文件也是我们最重要碰到的配置文件,利用properties读取这类文件到内存一行代码就欧科,比自己解析强大多了,这点很赞。

读取配置文件的大略代码如下:

public class LoadSample {      public static void main(String args[]) throws Exception {        Properties prop = new Properties();        FileInputStream fis =           new FileInputStream("sample.properties");        prop.load(fis);        prop.list(System.out);        System.out.println("\nThe foo property: " +            prop.getProperty("foo"));      }  }

第六行的load方法直接生产一个内存map,第九行就能get到对应的value了,简单快捷。

这里的第七行list方法是一个输出方法,这边是输出到console,也可以输出到文件等,就能实现内存写入配置文件了。

比如这样:

//通过list 方法将Properties写入Properties文件import java.io.IOException;import java.io.File;import java.io.FileInputStream;import java.io.PrintStream;import java.util.Properties;public class Test {    public static void main(String[] args) {        Properties p = new Properties();        p.setProperty("id","dean");        p.setProperty("password","123456");        try{            PrintStream fW = new PrintStream(new File("e:\\test1.properties"));          p.list(fW );} catch (IOException e) {          e.printStackTrace();        }    }}

这样就能把内存中的properties对象写入到文件中了。

另外一种配置形式是xml形式的,这种配置相对上面一种就少见一点。

xml形式的配置文件格式大略是这样:

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  <properties>  <comment>Hi</comment>  <entry key="foo">bar</entry>  <entry key="fu">baz</entry>  </properties>
读取xml配置跟读取kv配置没差别,就是把load换成xml对应的loadFromXML方法,代码大略是这样:

public class LoadSampleXML {      public static void main(String args[]) throws Exception {        Properties prop = new Properties();        FileInputStream fis =          new FileInputStream("sampleprops.xml");        prop.loadFromXML(fis);        prop.list(System.out);        System.out.println("\nThe foo property: " +            prop.getProperty("foo"));      }  }

把内存中的properties对象写入到xml文件中也和上面差不多,就是把list方法改成xml对应的storeToXML方法。

代码大略是这样:

import java.io.IOException;import java.io.File;import java.io.FileInputStream;import java.io.PrintStream;import java.util.Properties;public class Test {    public static void main(String[] args) {        Properties p = new Properties();        p.setProperty("id","dean");        p.setProperty("password","123456");        try{            PrintStream fW = new PrintStream(new File("e:\\test1.xml"));            p.storeToXML(fW,"test");        } catch (IOException e) {            e.printStackTrace();        }    }}
package stu; import java.io.*; import java.util.Properties; public class TestProperties {         public static void main(String args[]) throws IOException {                 testProperties();                 test1();         }         public static void testProperties() throws IOException {                 System.out.println("------------testProperties-------------");                 //将properties文件加载到输入字节流中                 InputStream is = new FileInputStream("D:\\myprojects\\lession4\\src\\stu\\ttt.properties");                 //创建一个Properties容器                 Properties prop = new Properties();                 //从流中加载properties文件信息                 prop.load(is);                 //循环输出配置信息                 for (Object key : prop.keySet()) {                         System.out.println(key + "=" + prop.get(key));                 }                 //定义一个输出流                 OutputStream os1 = new FileOutputStream("C:\\ttt.xml");                 OutputStream os2 = new FileOutputStream("C:\\ttt.properties");                 //从Properties对象导出导出到xml                 prop.storeToXML(os1, "我从properties导出的XML配置文件");                 //从Properties对象导出properties文件                 prop.store(os2, "我从properties导出的XML配置文件");                 is.close();                 os1.close();                 os2.close();                 //从xml加载配置信息,填充Properties容器                 prop.loadFromXML(new FileInputStream("C:\\ttt.xml"));                 //循环输出配置信息                 System.out.println("我从导出的xml加载配置文件信息!");                 for (Object key : prop.keySet()) {                         System.out.println(key + "=" + prop.get(key));                 }                 //修改Properties对象,并持久化到一个文件                 prop.put("呵呵呵", "嘎嘎嘎");                 OutputStream os3 = new FileOutputStream("C:\\ttt1.xml");                 prop.storeToXML(os3, "我从properties导出的XML配置文件");                 os3.close();         }         /**          * 以相对路径方式加载properties文件          *          * @throws IOException          */         public static void test1() throws IOException {                 System.out.println("------------test1-------------");                 Properties p = new Properties();                 p.load(TestProperties.class.getResourceAsStream("/stu/ttt.properties"));                 for (Object key : p.keySet()) {                         System.out.println(key + "=" + p.get(key));                 }         } }
java读取properties文件的六种方法 
使用j2se api读取properties文件的六种方法
1、使用java.util.properties类的load()方法
示例: inputstream in = lnew bufferedinputstream(new fileinputstream(name)) 
properties p = new properties() 
p.load(in) 
2、使用java.util.resourcebundle类的getbundle()方法
示例: resourcebundle rb = resourcebundle.getbundle(name locale.getdefault()) 
3、使用java.util.propertyresourcebundle类的构造函数
示例: inputstream in = new bufferedinputstream(new fileinputstream(name)) 
resourcebundle rb = new propertyresourcebundle(in) 

4、使用class变量的getresourceasstream()方法
示例: inputstream in = jproperties.class.getresourceasstream(name) 
properties p = new properties() 
p.load(in) 
5、使用class.getclassloader()所得到的java.lang.classloader的getresourceasstream()方法
示例: inputstream in = jproperties.class.getclassloader().getresourceasstream(name) 
properties p = new properties() 
p.load(in) 
6、使用java.lang.classloader类的getsystemresourceasstream()静态方法
示例: inputstream in = classloader.getsystemresourceasstream(name) 
properties p = new properties() 
p.load(in) 
补充
servlet中可以使用javax.servlet.servletcontext的getresourceasstream()方法
示例:inputstream in = context.getresourceasstream(path) 
properties p = new properties() 
p.load(in) 










0 0