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("\u672a\u6765");  
           System.out.println(str);  
    }

  
  
  
          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

結果:未來


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM