`
nbtlxx
  • 浏览: 249108 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
社区版块
存档分类
最新评论

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

分享到:
评论
2 楼 wangxiang243 2014-07-08  
文件保存为utf8编码格式就可以了吧
1 楼 rj2012 2013-11-29  
perfect

相关推荐

Global site tag (gtag.js) - Google Analytics