Properties获取数据乱码解决
Properties获取数据乱码解决
By shenweifeng
2012/12/28 In HangZhou 一、 原因
Properties调用load(InputStream)时,读取文件时使用的默认编码为ISO-8859-1;当我们讲中文放入到properties文件中,通过getProperty(key)获取值时,取到得数据是ISO-8859-1格式的,但是ISO-8859-1是不能识别中文的。
二、 解决
方法
快递客服问题件处理详细方法山木方法pdf计算方法pdf华与华方法下载八字理论方法下载
通过getProperty()获取的数据data既然是ISO-8859-1编码的,就通过data.getByte(“iso-8859-1”)获取获取,使用new String(data.getByte(“iso-8859-1”),”UTF-8”)进行转换。当然properties文件的编码类型需要和new String(Byte[],charst)中的第二个参数的编码类型相同
三、 Properties工具类
public class PropertyUtils {
private static final Logger logger =
LoggerFactory.getLogger(PropertyUtils.class);
private static Properties properties = new Properties();
static {
try {
//加载配置文件
properties.load(PropertyUtils.class
.getResourceAsStream("/properties/freemaker.properties"));
} catch (IOException e) {
logger.error(e.getMessage());
}
}
/**
* method:getValue{根据key获取value}
* @param key
* @return 属性文件中获取的value
*/
public static String getValue(String key){
String value = "";
try {
value=new
String(properties.getProperty(key).getBytes("iso-8859-1"),"
UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
}
return value;
}
public static Properties getProperties() {
return properties;
}
public static void setProperties(Properties properties) {
PropertyUtils.properties = properties;
}
}