在Java的內存中進行字節和字符的數據類型相互轉換非常常見,也有多種方法進行轉換,在此處為大家一一介紹。
1. String
String類提供了轉換到字節的方法,也提供了字節轉換到字符的構造方法,代碼入下所示:
String str = "這是一段字符串";
byte[] bytes = str.getBytes("UTF-8");
String newStr = new String(bytes, "UTF-8");
2.ByteToCharConverter & CharToByteConverter
這兩個類分別提供converAll()方法實現字節和字符的轉換,代碼如下所示:
ByteToCharConverter charConverter = ByteToCharConverter.getConverter("UTF-8");
char[] c = charConverter.convertAll(byteArray);
CharToByteConverter byteConverter = CharToByteConverter.getConverter("UTF-8");
byte[] b = byteConverter.convertAll(c);
3.Charset
方法2中的兩個類已經被Charset取代,Charset提供encode以及decode方法,分別對應char[]到byte[]的編碼已經byte[]到char[]的編碼,代碼如下:
String str = "這是一段字符串";
Charset charset = Charset.forName("UTF-8");
ByteBuffer byteBuffer = charset.encode(str);
CharBuffer charBuffer = charset.decode(byteBuffer);
4.ByteBuffer
ByteBuffer提供char和byte之間的軟轉換,他們之間的轉換不需要編碼與解碼,只是把一個16bit的char拆分成2個8bit的byte表示,他們的實際值并沒有被修改,僅僅是數據的數據類型做了轉換,代碼如下:
ByteBuffer heapByteBuffer = ByteBuffer.allocate(1024);
ByteBuffer byteBuffer = heapByteBuffer.putChar(c);