zoukankan      html  css  js  c++  java
  • java读取配置文件(properties)的时候,unicode码转utf-8

    有时我们在读取properties结尾的配置文件的时候,如果配置文件中有中文,那么我们读取到的是unicode码的中文,需要我们在转换一下,代码如下

    /**
         * 将配置文件中的Unicode 转 utf-8 汉字 
         * @param 原始字符串
         * @return  转换后的格式的字符串
         */
        public static String unicodeToChina(String str) {    
            Charset set = Charset.forName("UTF-16");    
            Pattern p = Pattern.compile("\\u([0-9a-fA-F]{4})");    
            Matcher m = p.matcher( str );    
            int start = 0 ;    
            int start2 = 0 ;    
            StringBuffer sb = new StringBuffer();    
            while( m.find( start ) ) {    
                start2 = m.start() ;    
                if( start2 > start ){    
                    String seg = str.substring(start, start2) ;    
                    sb.append( seg );    
                }    
                String code = m.group( 1 );    
                int i = Integer.valueOf( code , 16 );    
                byte[] bb = new byte[ 4 ] ;    
                bb[ 0 ] = (byte) ((i >> 8) & 0xFF );    
                bb[ 1 ] = (byte) ( i & 0xFF ) ;    
                ByteBuffer b = ByteBuffer.wrap(bb);    
                sb.append( String.valueOf( set.decode(b) ).trim() );    
                start = m.end() ;    
            }    
            start2 = str.length() ;    
            if( start2 > start ){    
                String seg = str.substring(start, start2) ;    
                sb.append( seg );    
            }    
            return sb.toString() ;    
        }  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    测试

         public static void main(String[] args) {
               String str = unicodeToChina("u672au6765");  
               System.out.println(str);  
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 1
    • 2
    • 3
    • 4
    • 5

    结果:未来

  • 相关阅读:
    js数组去重五种方法
    wm_concat 多行字符串拼接
    ORACLE WITH AS 简单用法
    layui laytpl 语法
    看懂Oracle执行计划
    GIT RM -R --CACHED 去掉已经托管在GIT上的文件
    sourceTree使用教程--拉取、获取
    SourceTree忽略文件和文件夹
    layui table 详细讲解
    利用POI实现下拉框级联
  • 原文地址:https://www.cnblogs.com/edgedance/p/6979668.html
Copyright © 2011-2022 走看看