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

    结果:未来

  • 相关阅读:
    opensuse tumbleweed中安装code
    树莓派中将caplock映射为esc键
    记录一次奇怪但是很有意义的程序编译警告
    新树莓派系统安装ROS记录
    程序的深挖
    intle官方手册下载
    slax linux的定制
    angular4 *ngFor获取index
    axios post传参后台无法接收问题
    AMD、CMD、CommonJs和 ES6对比
  • 原文地址:https://www.cnblogs.com/edgedance/p/6979668.html
Copyright © 2011-2022 走看看