在Java的內(nèi)存中進行字節(jié)和字符的數(shù)據(jù)類型相互轉(zhuǎn)換非常常見,也有多種方法進行轉(zhuǎn)換,在此處為大家一一介紹。
1. String
String類提供了轉(zhuǎn)換到字節(jié)的方法,也提供了字節(jié)轉(zhuǎn)換到字符的構(gòu)造方法,代碼入下所示:
String str = "這是一段字符串";
byte[] bytes = str.getBytes("UTF-8");
String newStr = new String(bytes, "UTF-8");
2.ByteToCharConverter & CharToByteConverter
這兩個類分別提供converAll()方法實現(xiàn)字節(jié)和字符的轉(zhuǎn)換,代碼如下所示:
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中的兩個類已經(jīng)被Charset取代,Charset提供encode以及decode方法,分別對應char[]到byte[]的編碼已經(jīng)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之間的軟轉(zhuǎn)換,他們之間的轉(zhuǎn)換不需要編碼與解碼,只是把一個16bit的char拆分成2個8bit的byte表示,他們的實際值并沒有被修改,僅僅是數(shù)據(jù)的數(shù)據(jù)類型做了轉(zhuǎn)換,代碼如下:
ByteBuffer heapByteBuffer = ByteBuffer.allocate(1024);
ByteBuffer byteBuffer = heapByteBuffer.putChar(c);