这篇文章主要介绍了XML作为属性文件的使用,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。

创新互联是一家专注于成都做网站、网站建设与策划设计,镇坪网站建设哪家好?创新互联做网站,专注于网站建设十年,网设计领域的专业建站公司;建站业务涵盖:镇坪等地区。镇坪做网站价格咨询:18980820575
我们通常会将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