properties 中文乱码问题的解决

在用properties处理配置信息时,发现有时出现中文乱码的问题,后经查资料得知是由于编码不一致引起的。于是解决之。

【原理解释】

我们用 API操作properties文件,如果获取的属性值是中文,为什么会出现乱码呢?

我们知道,如果编码(输出)和解码(读入)用的encoding是不一致的有可能会引起中文乱码问题,如果这两种encoding冲突,则你 基本上就中奖了。

1、假设如果我们创建properties文件用的encoding是GBK,我们写入了中 文

 2、Properties文件默认机制是采用ISO8859-1处理

3、我们用Properties.getProperty(String key)接口读取内容,这是时候得到的是乱码。因为想用ISO8859-1对GBK编码的内容进行解码

 4、我们把用Properties.getProperty(String key)接口读取内容转换为创建properties文件时用的encoding(GBK)不就解决问题了

【代码示例】 

  public class PropertiesUtil {

      /**

       * util class

       */

      private PropertiesUtil() {}

      

      /**

       * 指定编码获取properties文件中的属性值(解决中文乱码问 题)

       * 

      * @param properties   java.util.Properties

      * @param key              属性key

      * @return

      */

     public static String getProperty(Properties properties, String key, String encoding) throws UnsupportedEncodingException {

         //param check

         if (properties == null)

             return null;

         // 如果此时value是中文,则应该是乱码

         String value = properties.getProperty(key);

         if (value == null)

             return null;

         // 编码转换,从ISO8859-1转向指定编码

         value = new String(value.getBytes("ISO8859-1"), encoding);

         return value;

     }

 }

      

如果 你的应用创建中使用的系统默认编码,则如下转化:

PropertiesUtil.getProperty(properties, "TestKey", System.getProperty("file.encoding"));

PS:java中文乱码的问题会遇到不少,尤其是用字符流的时候。老早之前和乱码做过斗争,经验是 要搞清楚产生乱码的基本原理,然后再修理它

原文地址:https://www.cnblogs.com/toSeeMyDream/p/4377510.html