我们通常会将Java应用的配置参数保存在属性文件中,Java应用的属性文件可以是一个正常的基于key-value对,以properties为扩展名的文件,也可以是XML文件.

在本案例中,將会向大家介绍如何通过Java程序输出这两种格式的属性文件,并介绍如何从classpath中加载和使用这两种属性文件。
下面是案例程序代码:
PropertyFilesUtil.java

package com.journaldev.util;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import java.util.Set;public class PropertyFilesUtil {    public static void main(String[] args) throws IOException {        String propertyFileName = "DB.properties";        String xmlFileName = "DB.xml";        writePropertyFile(propertyFileName, xmlFileName);        readPropertyFile(propertyFileName, xmlFileName);        readAllKeys(propertyFileName, xmlFileName);        readPropertyFileFromClasspath(propertyFileName);    }    /**     * read property file from classpath     * @param propertyFileName     * @throws IOException     */    private static void readPropertyFileFromClasspath(String propertyFileName) throws IOException {        Properties prop = new Properties();        prop.load(PropertyFilesUtil.class.getClassLoader().getResourceAsStream(propertyFileName));        System.out.println(propertyFileName +" loaded from Classpath::db.host = "+prop.getProperty("db.host"));        System.out.println(propertyFileName +" loaded from Classpath::db.user = "+prop.getProperty("db.user"));        System.out.println(propertyFileName +" loaded from Classpath::db.pwd = "+prop.getProperty("db.pwd"));        System.out.println(propertyFileName +" loaded from Classpath::XYZ = "+prop.getProperty("XYZ"));    }    /**     * read all the keys from the given property files     * @param propertyFileName     * @param xmlFileName     * @throws IOException      */    private static void readAllKeys(String propertyFileName, String xmlFileName) throws IOException {        System.out.println("Start of readAllKeys");        Properties prop = new Properties();        FileReader reader = new FileReader(propertyFileName);        prop.load(reader);        Set<Object> keys= prop.keySet();        for(Object obj : keys){            System.out.println(propertyFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString()));        }        //loading xml file now, first clear existing properties        prop.clear();        InputStream is = new FileInputStream(xmlFileName);        prop.loadFromXML(is);        keys= prop.keySet();        for(Object obj : keys){            System.out.println(xmlFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString()));        }        //Now free all the resources        is.close();        reader.close();        System.out.println("End of readAllKeys");    }    /**     * This method reads property files from file system     * @param propertyFileName     * @param xmlFileName     * @throws IOException      * @throws FileNotFoundException      */    private static void readPropertyFile(String propertyFileName, String xmlFileName) throws FileNotFoundException, IOException {        System.out.println("Start of readPropertyFile");        Properties prop = new Properties();        FileReader reader = new FileReader(propertyFileName);        prop.load(reader);        System.out.println(propertyFileName +"::db.host = "+prop.getProperty("db.host"));        System.out.println(propertyFileName +"::db.user = "+prop.getProperty("db.user"));        System.out.println(propertyFileName +"::db.pwd = "+prop.getProperty("db.pwd"));        System.out.println(propertyFileName +"::XYZ = "+prop.getProperty("XYZ"));                //loading xml file now, first clear existing properties        prop.clear();        InputStream is = new FileInputStream(xmlFileName);        prop.loadFromXML(is);        System.out.println(xmlFileName +"::db.host = "+prop.getProperty("db.host"));        System.out.println(xmlFileName +"::db.user = "+prop.getProperty("db.user"));        System.out.println(xmlFileName +"::db.pwd = "+prop.getProperty("db.pwd"));        System.out.println(xmlFileName +"::XYZ = "+prop.getProperty("XYZ"));                //Now free all the resources        is.close();        reader.close();        System.out.println("End of readPropertyFile");    }    /**     * This method writes Property files into file system in property file     * and xml format     * @param fileName     * @throws IOException     */    private static void writePropertyFile(String propertyFileName, String xmlFileName) throws IOException {        System.out.println("Start of writePropertyFile");        Properties prop = new Properties();        prop.setProperty("db.host", "localhost");        prop.setProperty("db.user", "user");        prop.setProperty("db.pwd", "password");        prop.store(new FileWriter(propertyFileName), "DB Config file");        System.out.println(propertyFileName + " written successfully");        prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file");        System.out.println(xmlFileName + " written successfully");        System.out.println("End of writePropertyFile");    }}

当运行这段代码时,writePropertyFile 方法会在生成上述两种格式的属性文件,并將文件存储在工程的根目录下。
writePropertyFile 方法生成的两种属性文件内容:
DB.properties

#DB Config file#Fri Nov 16 11:16:37 PST 2012db.user=userdb.host=localhostdb.pwd=password

DB.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"><properties><comment>DB Config XML file</comment><entry key="db.user">user</entry><entry key="db.host">localhost</entry><entry key="db.pwd">password</entry></properties>

需要注意的是comment元素,我们在使用prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file");这段代码时第二个参数传入的是注释内容,如果传入null,生成的xml属性文件將没有comment元素。
控制台输出内容如下:

Start of writePropertyFileDB.properties written successfullyDB.xml written successfullyEnd of writePropertyFileStart of readPropertyFileDB.properties::db.host = localhostDB.properties::db.user = userDB.properties::db.pwd = passwordDB.properties::XYZ = nullDB.xml::db.host = localhostDB.xml::db.user = userDB.xml::db.pwd = passwordDB.xml::XYZ = nullEnd of readPropertyFileStart of readAllKeysDB.properties:: Key=db.user::value=userDB.properties:: Key=db.host::value=localhostDB.properties:: Key=db.pwd::value=passwordDB.xml:: Key=db.user::value=userDB.xml:: Key=db.host::value=localhostDB.xml:: Key=db.pwd::value=passwordEnd of readAllKeysException in thread "main" java.lang.NullPointerException    at java.util.Properties$LineReader.readLine(Properties.java:434)    at java.util.Properties.load0(Properties.java:353)    at java.util.Properties.load(Properties.java:341)    at com.journaldev.util.PropertyFilesUtil.readPropertyFileFromClasspath(PropertyFilesUtil.java:31)    at com.journaldev.util.PropertyFilesUtil.main(PropertyFilesUtil.java:21)

这里报了空指针异常,原因是生成的文件保存在工程的根目录下面,而读取时是从classpath下读取,將上面生成的两个属性文件拷贝到src下再次运行程序即可。

我们通常会将Java应用的配置参数保存在属性文件中,Java应用的属性文件可以是一个正常的基于key-value对,以properties为扩展名的文件,也可以是XML文件.
在本案例中,將会向大家介绍如何通过Java程序输出这两种格式的属性文件,并介绍如何从classpath中加载和使用这两种属性文件。
下面是案例程序代码:
PropertyFilesUtil.java

package com.journaldev.util;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import java.util.Set;public class PropertyFilesUtil {    public static void main(String[] args) throws IOException {        String propertyFileName = "DB.properties";        String xmlFileName = "DB.xml";        writePropertyFile(propertyFileName, xmlFileName);        readPropertyFile(propertyFileName, xmlFileName);        readAllKeys(propertyFileName, xmlFileName);        readPropertyFileFromClasspath(propertyFileName);    }    /**     * read property file from classpath     * @param propertyFileName     * @throws IOException     */    private static void readPropertyFileFromClasspath(String propertyFileName) throws IOException {        Properties prop = new Properties();        prop.load(PropertyFilesUtil.class.getClassLoader().getResourceAsStream(propertyFileName));        System.out.println(propertyFileName +" loaded from Classpath::db.host = "+prop.getProperty("db.host"));        System.out.println(propertyFileName +" loaded from Classpath::db.user = "+prop.getProperty("db.user"));        System.out.println(propertyFileName +" loaded from Classpath::db.pwd = "+prop.getProperty("db.pwd"));        System.out.println(propertyFileName +" loaded from Classpath::XYZ = "+prop.getProperty("XYZ"));    }    /**     * read all the keys from the given property files     * @param propertyFileName     * @param xmlFileName     * @throws IOException      */    private static void readAllKeys(String propertyFileName, String xmlFileName) throws IOException {        System.out.println("Start of readAllKeys");        Properties prop = new Properties();        FileReader reader = new FileReader(propertyFileName);        prop.load(reader);        Set<Object> keys= prop.keySet();        for(Object obj : keys){            System.out.println(propertyFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString()));        }        //loading xml file now, first clear existing properties        prop.clear();        InputStream is = new FileInputStream(xmlFileName);        prop.loadFromXML(is);        keys= prop.keySet();        for(Object obj : keys){            System.out.println(xmlFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString()));        }        //Now free all the resources        is.close();        reader.close();        System.out.println("End of readAllKeys");    }    /**     * This method reads property files from file system     * @param propertyFileName     * @param xmlFileName     * @throws IOException      * @throws FileNotFoundException      */    private static void readPropertyFile(String propertyFileName, String xmlFileName) throws FileNotFoundException, IOException {        System.out.println("Start of readPropertyFile");        Properties prop = new Properties();        FileReader reader = new FileReader(propertyFileName);        prop.load(reader);        System.out.println(propertyFileName +"::db.host = "+prop.getProperty("db.host"));        System.out.println(propertyFileName +"::db.user = "+prop.getProperty("db.user"));        System.out.println(propertyFileName +"::db.pwd = "+prop.getProperty("db.pwd"));        System.out.println(propertyFileName +"::XYZ = "+prop.getProperty("XYZ"));                //loading xml file now, first clear existing properties        prop.clear();        InputStream is = new FileInputStream(xmlFileName);        prop.loadFromXML(is);        System.out.println(xmlFileName +"::db.host = "+prop.getProperty("db.host"));        System.out.println(xmlFileName +"::db.user = "+prop.getProperty("db.user"));        System.out.println(xmlFileName +"::db.pwd = "+prop.getProperty("db.pwd"));        System.out.println(xmlFileName +"::XYZ = "+prop.getProperty("XYZ"));                //Now free all the resources        is.close();        reader.close();        System.out.println("End of readPropertyFile");    }    /**     * This method writes Property files into file system in property file     * and xml format     * @param fileName     * @throws IOException     */    private static void writePropertyFile(String propertyFileName, String xmlFileName) throws IOException {        System.out.println("Start of writePropertyFile");        Properties prop = new Properties();        prop.setProperty("db.host", "localhost");        prop.setProperty("db.user", "user");        prop.setProperty("db.pwd", "password");        prop.store(new FileWriter(propertyFileName), "DB Config file");        System.out.println(propertyFileName + " written successfully");        prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file");        System.out.println(xmlFileName + " written successfully");        System.out.println("End of writePropertyFile");    }}

当运行这段代码时,writePropertyFile 方法会在生成上述两种格式的属性文件,并將文件存储在工程的根目录下。
writePropertyFile 方法生成的两种属性文件内容:
DB.properties

#DB Config file#Fri Nov 16 11:16:37 PST 2012db.user=userdb.host=localhostdb.pwd=password

DB.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE properties SYSTEM " <properties><comment>DB Config XML file</comment><entry key="db.user">user</entry><entry key="db.host">localhost</entry><entry key="db.pwd">password</entry></properties>

需要注意的是comment元素,我们在使用prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file");这段代码时第二个参数传入的是注释内容,如果传入null,生成的xml属性文件將没有comment元素。
控制台输出内容如下:

Start of writePropertyFileDB.properties written successfullyDB.xml written successfullyEnd of writePropertyFileStart of readPropertyFileDB.properties::db.host = localhostDB.properties::db.user = userDB.properties::db.pwd = passwordDB.properties::XYZ = nullDB.xml::db.host = localhostDB.xml::db.user = userDB.xml::db.pwd = passwordDB.xml::XYZ = nullEnd of readPropertyFileStart of readAllKeysDB.properties:: Key=db.user::value=userDB.properties:: Key=db.host::value=localhostDB.properties:: Key=db.pwd::value=passwordDB.xml:: Key=db.user::value=userDB.xml:: Key=db.host::value=localhostDB.xml:: Key=db.pwd::value=passwordEnd of readAllKeysException in thread "main" java.lang.NullPointerException    at java.util.Properties$LineReader.readLine(Properties.java:434)    at java.util.Properties.load0(Properties.java:353)    at java.util.Properties.load(Properties.java:341)    at com.journaldev.util.PropertyFilesUtil.readPropertyFileFromClasspath(PropertyFilesUtil.java:31)    at com.journaldev.util.PropertyFilesUtil.main(PropertyFilesUtil.java:21)

以上就是Java&Xml教程(十)XML作为属性文件使用的内容,更多相关内容请关注PHP中文网(www.php.cn)!

更多相关文章

  1. xml学习(1)xml的几种文件格式
  2. XML—XML文件约束之DTD详解
  3. xml学习(4) 创建xml 文件
  4. XML文件导入EXCEL
  5. xml学习(7) .net 获取xml节点或者属性最大值
  6. 使用 XML 文件记录操作日志
  7. XMLTextReader和XmlDocument读取XML文件的比较
  8. 创建带有关联的 XML 架构的 XML 文件 && 从 XML 文件创建 XML 架
  9. 将图片读入到Dom中,并将其存为xml文件

随机推荐

  1. Thinkphp 使用原生类
  2. 如果db query A没有返回足够的结果,请运行
  3. PHP基础之脚本传参
  4. 如何解决一段时间真正的循环,因为它昂贵且
  5. PHP强大包括处理错误?
  6. Laravel将动态输入数据数组保存到数据库
  7. 在rhel5版本下安装mysql+apache+php实战
  8. 在单个测试中断言多个条件,还是分成多个测
  9. 在PHP中如何取得两个日期时间相减的结果,
  10. 函数不返回“functions.php”中的值