我们通常会将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 propertiesprop.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 resourcesis.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 propertiesprop.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 resourcesis.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 2012
db.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");这段代码时第二个参数传入的是注释内容,如果传入null,生成的xml属性文件將没有comment元素。
控制台输出内容如下:

Start of writePropertyFile
DB.properties written successfully
DB.xml written successfully
End of writePropertyFile
Start of readPropertyFile
DB.properties::db.host = localhost
DB.properties::db.user = user
DB.properties::db.pwd = password
DB.properties::XYZ = null
DB.xml::db.host = localhost
DB.xml::db.user = user
DB.xml::db.pwd = password
DB.xml::XYZ = null
End of readPropertyFile
Start of readAllKeys
DB.properties:: Key=db.user::value=user
DB.properties:: Key=db.host::value=localhost
DB.properties:: Key=db.pwd::value=password
DB.xml:: Key=db.user::value=user
DB.xml:: Key=db.host::value=localhost
DB.xml:: Key=db.pwd::value=password
End of readAllKeys
Exception in thread "main" java.lang.NullPointerExceptionat 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下再次运行程序即可。

转载于:https://www.cnblogs.com/lanzhi/p/6468333.html

JavaXml教程(十)XML作为属性文件使用相关推荐

  1. ComicEnhancerPro 系列教程十八:JPG文件长度与质量

    作者:马健 邮箱:stronghorse_mj@hotmail.com 主页:http://www.comicer.com/stronghorse/ 发布:2017.07.23 教程十八:JPG文件长 ...

  2. 加载oracle属性文件,关于属性文件的详细介绍

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

  3. JavaXml教程(一)简介

    XML是广泛用于数据传输和存储的技术.Java语言提供个各种各样的API来解析XML,例如DOM.SAX.StAX.JAXB.也还有一些其他的API用于解析XML,例如JDOM.本教程的目的是探索使用 ...

  4. java log4j 代码配置文件_除了Log4jXML、属性文件和源代码(主要是Java)之外的配置日志的方法?...

    我在看一些应用程序的源代码.它正在使用 Spring框架.Apache瓦片.JSP.Log4J.Java.JavaScript.jQuery.JQPrand.Jsch 等. 我知道日志是在哪里创建的. ...

  5. 【Visual C++】游戏开发笔记四十四 浅墨DirectX教程十二 网格模型和X文件使用面面观

    本系列文章由zhmxy555(毛星云)编写,转载请注明出处. 文章链接: http://blog.csdn.net/zhmxy555/article/details/8586540 作者:毛星云(浅墨 ...

  6. 【Visual C++】游戏开发笔记四十四 浅墨DirectX教程十二 网格模型和X文件使用面面观...

    本系列文章由zhmxy555(毛星云)编写,转载请注明出处. 文章链接:http://blog.csdn.net/zhmxy555/article/details/8586540 作者:毛星云(浅墨) ...

  7. C#实用教程-操作xml文件

    C#实用教程-操作xml文件 C#实用教程-操作xml文件 引言:什么是xml文件 Xml的特征 Xml的格式 与HTML的区别 对Xml进行操作 读取xml文件: 当前xml文件内容如下: 创建xm ...

  8. Wix 安装部署教程(十六) -- 自动生成多语言文件

    Wix 安装部署教程(十六) -- 自动生成多语言文件 原文:Wix 安装部署教程(十六) -- 自动生成多语言文件 因为持续集成需要,所有项目编译完之后生成一个多语言的安装包.之前生成mst文件都是 ...

  9. Wix 安装部署教程(十二) -- 自动更新WXS文件

    原文:Wix 安装部署教程(十二) -- 自动更新WXS文件 上一篇分享了一个QuickWIX,用来对比两个工程前后的差异,但是这样还是很繁琐,而且昨天发现有Bug,目录对比有问题.这次改变做法,完全 ...

最新文章

  1. 04.Java网络编程(转载)
  2. jaxb注解使用_使用JAXB时
  3. python数据库实现注册函数_python 函数 之 用户注册register()
  4. HTML+Javascript制作拼图小游戏详解(一)
  5. 编译用于高放射性环境的应用程序
  6. 怎么使用PDF编辑器在PDF中插入图片?PDF插入图片的教程
  7. Java项目-食堂菜品点评系统(SpringBoot + SpringSecurity + Thymeleaf + Redis)
  8. php 中文手册下载
  9. 最简单的单片机c语言程序,单片机的C语言编程基础知识(初学注意)
  10. lvds传输距离标准_LVDS视频传输—LVDS收发传输经验教训计划总结
  11. 计算机学霸小黄是谁,人人网惊现“小黄鸡”火成一片 大学生调侃“你是学霸派来的么?”...
  12. UOS/Deepin 常用文本代码编辑器推荐及安装
  13. Linux下rsh服务配置
  14. vijos P1263 单挑女飞贼
  15. 百度地图 --- 自定义标注点
  16. 英雄联盟无限重新连接服务器,英雄联盟无法连接服务器你想重新连接吗
  17. 人生应该要有梦想,万一见鬼了呢?!
  18. 对存储过程进行加密和解密(SQL 2008/SQL 2012)
  19. GeoGebra画傅里叶级数(三角函数积分 or 复变函数积分)
  20. 智能语音之远场关键词识别实践(一)

热门文章

  1. Spread for Windows Forms快速入门(1)---开始使用Spread
  2. 微软概述 Windows Server 2008 的定价、包装及授权
  3. YII CDbCriteria 的一些常用方法记录
  4. 解决Android 启动模拟器是出现“Failed to allocate memory: 8”错误提示
  5. 浏览器记住密码之后,input背景变黄
  6. 【算法】N Queens Problem
  7. MongoDB副本集配置系列四:节点的关闭顺序
  8. OJ 169 Majority Element
  9. VS2008下配置WTL开发环境
  10. mysql反模式_MongoDB报表实例 -- 标签成员方案