溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

XML作為屬性文件的使用

發(fā)布時(shí)間:2020-07-08 11:06:12 來源:億速云 閱讀:96 作者:Leah 欄目:編程語言

這篇文章主要介紹了XML作為屬性文件的使用,具有一定借鑒價(jià)值,需要的朋友可以參考下。下面就和我一起來看看吧。

我們通常會(huì)將Java應(yīng)用的配置參數(shù)保存在屬性文件中,Java應(yīng)用的屬性文件可以是一個(gè)正常的基于key-value對(duì),以properties為擴(kuò)展名的文件,也可以是XML文件.

在本案例中,將會(huì)向大家介紹如何通過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");
    }

}

當(dāng)運(yùn)行這段代碼時(shí),writePropertyFile 方法會(huì)在生成上述兩種格式的屬性文件,并將文件存儲(chǔ)在工程的根目錄下。
writePropertyFile 方法生成的兩種屬性文件內(nèi)容:
DB.properties

#DB Config file#Fri Nov 16 11:16:37 PST 2012db.user=user
db.host=localhost
db.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");這段代碼時(shí)第二個(gè)參數(shù)傳入的是注釋內(nèi)容,如果傳入null,生成的xml屬性文件將沒有comment元素。
控制臺(tái)輸出內(nèi)容如下:

Start of writePropertyFile
DB.properties written successfully
DB.xml written successfully
End of writePropertyFile
Start 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 = null
End of readPropertyFile
Start 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=password
End of readAllKeys
Exception 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)

這里報(bào)了空指針異常,原因是生成的文件保存在工程的根目錄下面,而讀取時(shí)是從classpath下讀取,將上面生成的兩個(gè)屬性文件拷貝到src下再次運(yùn)行程序即可。

我們通常會(huì)將Java應(yīng)用的配置參數(shù)保存在屬性文件中,Java應(yīng)用的屬性文件可以是一個(gè)正常的基于key-value對(duì),以properties為擴(kuò)展名的文件,也可以是XML文件.
在本案例中,將會(huì)向大家介紹如何通過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");
    }

}

當(dāng)運(yùn)行這段代碼時(shí),writePropertyFile 方法會(huì)在生成上述兩種格式的屬性文件,并將文件存儲(chǔ)在工程的根目錄下。
writePropertyFile 方法生成的兩種屬性文件內(nèi)容:
DB.properties

#DB Config file#Fri Nov 16 11:16:37 PST 2012db.user=user
db.host=localhost
db.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");這段代碼時(shí)第二個(gè)參數(shù)傳入的是注釋內(nèi)容,如果傳入null,生成的xml屬性文件將沒有comment元素。
控制臺(tái)輸出內(nèi)容如下:

Start of writePropertyFile
DB.properties written successfully
DB.xml written successfully
End of writePropertyFile
Start 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 = null
End of readPropertyFile
Start 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=password
End of readAllKeys
Exception 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)

以上就是XML作為屬性文件的使用的詳細(xì)內(nèi)容了,看完之后是否有所收獲呢?如果想了解更多相關(guān)內(nèi)容,歡迎來億速云行業(yè)資訊!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI