Java 读取配置文件

config.properties

配置文件中的中文需要转码为unicode

key1 = value1
key2 = value2
key3 = value3
\u8bed\u8a00 = \u4e2d\u6587

xml.properties

需要添加 dtd

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<entry key="key5">test</entry>
	<entry key="key6">10</entry>
	<entry key="唔">哈哈</entry>
</properties>

读取类

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.InvalidPropertiesFormatException;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * .properties 中文需要转换为unicode 编码    https://www.w3cschool.cn/tools/index?name=unicode_chinese
 * 
 * src/main/java 和 src/main/resources下的配置文件其实在同一目录下 -> classes
 * 
 * @author yz20537
 *
 */
public class ConfigurationUtils {
	
	public static void main(String[] args) throws IOException {
		
		//read config.properties
		resourceBundlePropertiesReader("config");				//put the file src/main/java
		resourceBundlePropertiesReader("resources");			//put the file src/main/resources
		classStreamPropertiesReader("/config.properties");		//put the file src/main/java
		classStreamPropertiesReader("/resources.properties");	//put the file src/main/resources
		
		//read config.xml
		xmlReader("/config.xml");		//put the file src/main/java
		xmlReader("/resources.xml");	//put the file src/main/resources

		
		
		System.out.println(configurationMap);
	}

	private static Map<String, String> configurationMap = new HashMap<String, String>();

	static void resourceBundlePropertiesReader(String path) {
		ResourceBundle resource = ResourceBundle.getBundle(path);
		Enumeration<String> keys = resource.getKeys();
		while (keys.hasMoreElements()) {
			String key = keys.nextElement();
			configurationMap.put(key, resource.getString(key));
		}
	}

	static void classStreamPropertiesReader(String path) throws IOException {
		Properties props = new Properties();
		InputStream in = ConfigurationUtils.class.getResourceAsStream(path);
		props.load(in);
		fromPropertiesToMap(props);
		in.close();
	}

	static void xmlReader(String path) throws InvalidPropertiesFormatException, IOException{
		Properties properties = new Properties();
		InputStream inputStream =ConfigurationUtils.class.getResourceAsStream(path);
		properties.loadFromXML(inputStream);
		fromPropertiesToMap(properties);
		inputStream.close();
		
	}
	
	static void fromPropertiesToMap(Properties props){
		Enumeration<Object> keys = props.keys();
		while (keys.hasMoreElements()) {
			String key = keys.nextElement().toString();
			configurationMap.put(key, props.getProperty(key));
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值