java.util.Properties 乱码问题解决方案

今天碰到一个乱码问题,很是奇怪。
小弟做了个system.properties文件
包含简单的配置属性, 但是每次读取出来中文乱码。
后来查看了资料才知道Properties默认的字符串是ISO8859-1。
解决办法:
将获取的字符串,重新构造一个基于UTF-8的字符串。

str = new String(value.getBytes("ISO8859-1"), "UTF-8");

下面是具体代码。


searchServerIp=localhost
searchServerPort=8889
serverTitle=基于Lucene在线客服软件Beta 1.0|Server
clientTitle=基于Lucene在线客服软件Beta 1.0|Client
firstTime=1000
period=1000*60*30



/**
*
*/
package net.tuolian.product.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
* @author sean
*
* 系统配置类 读取配置文件
*
*/
public class Config {
public static Config instance;
static Properties prop;

private Config() {
prop = new Properties();
try {
prop.load(new FileInputStream("system.properties"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 单例模式
*
* @return
*/
public static Config newInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
}

/**
*
* @param key
* @return
*/
public static String getProperty(String key) {
if(instance == null){
instance = Config.newInstance();
}

if (key == null) {
return null;
}

String value = prop.getProperty(key);
String str = null;
try {
//进行编码转换,解决问题
str = new String(value.getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值