Java 将属性文件转换为 XML 文件

Java 将属性文件转换为 XML 文件

原文: https://howtodoinjava.com/xml/convert-properties-to-xml/

Properties对象或任何现有.properties文件创建 XML 文件的 Java 示例。

从属性文件创建 XML 文件

要将属性文件转换为 XML 文件,最好的方法是使用java.util.Properties类。 流程是:

  1. 将属性文件加载到java.util.java.util.Properties类对象中。
  2. 使用Properties.storeToXML()方法将内容写为 XML。
package com.howtodoinjava.demo.xml;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import javax.xml.stream.XMLStreamException;

public class PropertiesToXML 
{
	public static void main(String[] args) throws XMLStreamException, 
                                     InvalidPropertiesFormatException, IOException 
	{
		String inPropertiesFile = "application.properties";
		String outXmlFile = "applicationProperties.xml";

		InputStream is = new FileInputStream(inPropertiesFile);	//Input file
		OutputStream os = new FileOutputStream(outXmlFile);		//Output file

		Properties props = new Properties();
		props.load(is);

		props.storeToXML(os, "application.properties","UTF-8");
	}
}

输入属性文件

#Disable batch job's auto start 
spring.batch.job.enabled=false
spring.main.banner-mode=off

#batch input files location
input.dir=c:/temp/input

输出 XML 文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>application.properties</comment>
	<entry key="input.dir">c:/temp/input</entry>
	<entry key="spring.batch.job.enabled">false</entry>
	<entry key="spring.main.banner-mode">off</entry>
</properties>

将我的问题放在评论部分。

学习愉快!