Java&Xml 자습서(10) XML을 속성 파일로 사용
일반적으로 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)!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











이 기사에서는 가장 많이 묻는 Java Spring 면접 질문과 자세한 답변을 보관했습니다. 그래야 면접에 합격할 수 있습니다.

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다

Java의 TimeStamp to Date 안내. 여기서는 소개와 예제와 함께 Java에서 타임스탬프를 날짜로 변환하는 방법에 대해서도 설명합니다.

캡슐은 3 차원 기하학적 그림이며, 양쪽 끝에 실린더와 반구로 구성됩니다. 캡슐의 부피는 실린더의 부피와 양쪽 끝에 반구의 부피를 첨가하여 계산할 수 있습니다. 이 튜토리얼은 다른 방법을 사용하여 Java에서 주어진 캡슐의 부피를 계산하는 방법에 대해 논의합니다. 캡슐 볼륨 공식 캡슐 볼륨에 대한 공식은 다음과 같습니다. 캡슐 부피 = 원통형 볼륨 2 반구 볼륨 안에, R : 반구의 반경. H : 실린더의 높이 (반구 제외). 예 1 입력하다 반경 = 5 단위 높이 = 10 단위 산출 볼륨 = 1570.8 입방 단위 설명하다 공식을 사용하여 볼륨 계산 : 부피 = π × r2 × h (4

Java는 초보자와 숙련된 개발자 모두가 배울 수 있는 인기 있는 프로그래밍 언어입니다. 이 튜토리얼은 기본 개념부터 시작하여 고급 주제를 통해 진행됩니다. Java Development Kit를 설치한 후 간단한 "Hello, World!" 프로그램을 작성하여 프로그래밍을 연습할 수 있습니다. 코드를 이해한 후 명령 프롬프트를 사용하여 프로그램을 컴파일하고 실행하면 "Hello, World!"가 콘솔에 출력됩니다. Java를 배우면 프로그래밍 여정이 시작되고, 숙달이 깊어짐에 따라 더 복잡한 애플리케이션을 만들 수 있습니다.

Spring Boot는 강력하고 확장 가능하며 생산 가능한 Java 응용 프로그램의 생성을 단순화하여 Java 개발에 혁명을 일으킨다. Spring Ecosystem에 내재 된 "구성에 대한 협약"접근 방식은 수동 설정, Allo를 최소화합니다.

간단해진 Java: 강력한 프로그래밍을 위한 초보자 가이드 소개 Java는 모바일 애플리케이션에서 엔터프라이즈 수준 시스템에 이르기까지 모든 분야에서 사용되는 강력한 프로그래밍 언어입니다. 초보자의 경우 Java의 구문은 간단하고 이해하기 쉬우므로 프로그래밍 학습에 이상적인 선택입니다. 기본 구문 Java는 클래스 기반 객체 지향 프로그래밍 패러다임을 사용합니다. 클래스는 관련 데이터와 동작을 함께 구성하는 템플릿입니다. 다음은 간단한 Java 클래스 예입니다. publicclassPerson{privateStringname;privateintage;
