java读取properties文件,中文乱码处理

解决办法有两种:

 

一、对属性配置文件进行转码处理

jdk安装完成后,会自带有native2ascii工具,可将属性配置文件中的中文字符转换成Unicode转义符,如汉字“中国”转换结果为“\u4e2d\u56fd”,这样读取时,就能正常显示中文了。

 

二、读取后,通过程序进行转码

Properties在load加载属性文件时,使用的是ISO-8859-1编码,我们可以在将属性内容读取后,再次进行一次编码即可(如utf-8,gbk)。

例子:

private static Properties prop = new Properties();
	static{
		try {
			prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf.properties"));
			
			//转码处理
			Set<Object> keyset = prop.keySet();
			Iterator<Object> iter = keyset.iterator();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				String newValue = null;
				try {
					//属性配置文件自身的编码
					String propertiesFileEncode = "utf-8";
					newValue = new String(prop.getProperty(key).getBytes("ISO-8859-1"),propertiesFileEncode);
				} catch (UnsupportedEncodingException e) {
					newValue = prop.getProperty(key);
				}
				prop.setProperty(key, newValue);
			}
		} catch (Exception e) {
			log.error("读取配置文件conf.properties出错!", e);
		}
	}

 

http://huangqiqing123.iteye.com/blog/1833854

你可能感兴趣的:(java,properties)