java读取*.properties配置文件时,中文乱码解决方法

3/8/2017来源:ASP.NET技巧人气:1352

之前项目中用到的代码块(读取配置文件会乱码):

public class PRopertiesConfig { private static Logger log = Logger.getLogger(PropertiesConfig.class); public PropertiesConfig() { } private static Properties props = new Properties(); static { try { props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("propertyconfig.properties")); } catch (FileNotFoundException e) { log.error(e); } catch (IOException e) { log.error(e); } } public static String getValue(String key) { return props.getProperty(key); } }

但是当配置文件中存在如下类型的key=value时,会出现value乱码

user_name=王大力

此时读取到的“王大力“乱码,解决方法(更改静态代码块):

static { try { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("msgconfig.properties"); BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); props.load(bf); } catch (FileNotFoundException e) { log.error(e); } catch (IOException e) { log.error(e); } }

这样读到的值不会乱码。