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));
}
}
}