首页 > 编程 > Java > 正文

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

2019-11-06 08:19:37
字体:
来源:转载
供稿:网友

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

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

这样读到的值不会乱码。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表