当前位置: 代码迷 >> 综合 >> String 与 UTF-8 byte 数组的相互转化
  详细解决方案

String 与 UTF-8 byte 数组的相互转化

热度:26   发布时间:2024-02-02 06:12:56.0

String 与 UTF-8 byte 数组的相互转化


String testStr = "1234qwerty";

        // String 转 UTF-8 byte 数组
byte[] inputByte = testStr.getBytes( "UTF-8" );

 

        // UTF-8 byte 数组转为 string,方法 1
String st = new String( inputByte, "utf-8" );
System.out.println( st );                      // 打印 1234qwerty

 

        // UTF-8 byte 数组转为 string,方法 2
StringBuffer sbf = new StringBuffer();

        for ( int i = 0; i < inputByte.length; i++ ) {
sbf.append( ( char ) inputByte[ i ] );
}

        System.out.println( sbf.toString() );     // 打印 1234qwerty

  相关解决方案