Java&Xml 자습서(10) XML을 속성 파일로 사용

黄舟
풀어 주다: 2017-02-22 14:58:35
원래의
1831명이 탐색했습니다.

일반적으로 Java 애플리케이션의 구성 매개변수는 속성 파일에 저장됩니다. Java 애플리케이션의 속성 파일은 속성이 확장자로 포함된 키-값 쌍을 기반으로 하는 일반 파일일 수도 있고

이 경우 Java 프로그램을 통해 이 두 가지 형식의 속성 파일을 출력하는 방법과 클래스 경로에서 이 두 가지 속성 파일을 로드하여 사용하는 방법을 소개합니다.
다음은 케이스 프로그램 코드입니다.
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=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>
로그인 후 복사

주석 요소는 우리가 prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file"); 코드를 조각할 때 두 번째 매개변수가 주석 내용에 전달됩니다. null이 전달되면 생성된 xml 속성 파일에 주석 요소가 없습니다.
콘솔 출력은 다음과 같습니다.

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)
로그인 후 복사

여기서 널 포인터 예외가 보고됩니다. 그 이유는 생성된 파일이 프로젝트의 루트 디렉터리에 저장되며 읽을 때 다음에서 읽혀지기 때문입니다. 위의 생성된 파일은 두 개의 속성 파일을 src에 복사하고 프로그램을 다시 실행합니다.

일반적으로 Java 애플리케이션의 구성 매개변수는 속성 파일에 저장됩니다. Java 애플리케이션의 속성 파일은 속성이 확장자로 포함된 키-값 쌍을 기반으로 하는 일반 파일일 수도 있고 XML 파일일 수도 있습니다.
이 경우 Java 프로그램을 통해 이 두 가지 형식의 속성 파일을 출력하는 방법과 클래스 경로에서 이 두 가지 속성 파일을 로드하고 사용하는 방법을 소개합니다.
다음은 케이스 프로그램 코드입니다.
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=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>
로그인 후 복사

주석 요소는 우리가 prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file"); 코드를 조각할 때 두 번째 매개변수가 주석 내용에 전달됩니다. null이 전달되면 생성된 xml 속성 파일에 주석 요소가 없습니다.
콘솔 출력 내용은 다음과 같습니다.

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)
로그인 후 복사

위는 Java&Xml Tutorial(10) XML을 속성 파일로 담은 내용입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.kr)를 참고해주세요. .php.cn)!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!