Java中的String类和编码转换


构造方法:

String(byte[] bytes, int offset, int length) 
          通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。 
String(byte[] bytes, int offset, int length, Charset charset) 
          通过使用指定的 charset 解码指定的 byte 子数组,构造一个新的 String。 
String(byte[] bytes, int offset, int length, String charsetName) 
          通过使用指定的字符集解码指定的 byte 子数组,构造一个新的 String。  
String(char[] value, int offset, int count) 
          分配一个新的 String,它包含取自字符数组参数一个子数组的字符。 
String(int[] codePoints, int offset, int count) 
          分配一个新的 String,它包含 Unicode 代码点数组参数一个子数组的字符。

将“南山南”转换为UTF-8字节码

import java.nio.*;
String str = "南山南";
Charset charset_utf8 = Charset.forName("utf-8");
ByteBuffer buff = charset_utf8.encode(str);
byte[] bArr = new byte[buff.remaining()];
buff.get(bArr); 

把字符串以指定编码转为byte[]和把byte[]以指定编码转为字符串。

public static void Utf8ToUnicode() throws UnsupportedEncodingException {
    String str="中文";        
    byte[] bArr = str.getBytes("unicode");  //bArr[0]=fe,bArr[1]=ff;从bArr[2]开始为编码内容
    String str1 = new String(bArr, "utf16");  //utf16和unicode编码一样
    System.out.println(str1);
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM