使用java.util.Properties
工具类代码:
package com.guide.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.HashMap;
import java.util.Properties;
/**
* Desc:properties文件获取工具类
*
*/
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
private static Properties props;
synchronized static public HashMap<String, String> loadProps(String prop){
HashMap<String, String> map = new HashMap<>();
logger.info("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
try {
/*第一种,通过类加载器进行获取properties文件流*/
in = PropertyUtil.class.getClassLoader().getResourceAsStream(prop);
/*第二种,通过类进行获取properties文件流*/
//in = PropertyUtil.class.getResourceAsStream(prop);
props.load(in);
} catch (FileNotFoundException e) {
logger.error("properties文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("properties文件流关闭出现异常");
}
}
logger.info("加载properties文件内容完成...........");
logger.info("properties文件内容:" + props);
for(Object i:props.keySet()){
map.put((String)i,props.getProperty((String)i));
}
return map;
}
}
java.util.Properties类中的load(InputStream inStream)方法如下:
/**
* Reads a property list (key and element pairs) from the input
* byte stream. The input stream is in a simple line-oriented
* format as specified in
* {@link #load(java.io.Reader) load(Reader)} and is assumed to use
* the ISO 8859-1 character encoding; that is each byte is one Latin1
* character. Characters not in Latin1, and certain special characters,
* are represented in keys and elements using Unicode escapes as defined in
* section 3.3 of
* <cite>The Java™ Language Specification</cite>.
* <p>
* The specified stream remains open after this method returns.
*
* @param inStream the input stream.
* @exception IOException if an error occurred when reading from the
* input stream.
* @throws IllegalArgumentException if the input stream contains a
* malformed Unicode escape sequence.
* @since 1.2
*/
public synchronized void load(InputStream inStream) throws IOException {
load0(new LineReader(inStream));
}
其中默认的编码格式是iso-8859-1.
但是Properties中还有一个传递Reader参数的方法,我们可以使用Reader来包装接收的InputStream
BufferedReader bf = new BufferedReader(new InputStreamReader(in, "UTF-8"));
props.load(in);
使用Spring框架中的org.springframework.core.io.support.PropertiesLoaderUtils
private static Properties springloadprop() {
EncodedResource encodedResource = new EncodedResource(new ClassPathResource("specialcity.properties"), "UTF-8");
try {
props = PropertiesLoaderUtils.loadProperties(encodedResource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return props;
}
OK