public class CharsetTransform { public static void main(String[] args) throws Exception {// Properties properties = System.getProperties();// for (Object key : properties.keySet()) {// String name = (String) key;// System.out.println(name + "------>" + properties.get(key));// } //file.encoding------>UTF-8 // 創建簡體中文對應的Charset Charset cn = Charset.forName("UTF-8"); // 獲取cn對象對應的編碼器和解碼器 CharsetEncoder cnEncoder = cn.newEncoder(); CharsetDecoder cnDecoder = cn.newDecoder(); // 創建一個CharBuffer對象 CharBuffer cbuff = CharBuffer.allocate(20); cbuff.put('隨'); cbuff.put('便'); cbuff.flip(); // 將CharBuffer中的字符序列轉換成字節序列 ByteBuffer bbuff = cnEncoder.encode(cbuff); // 循環訪問ByteBuffer中的每個字節 for (int i = 0; i < bbuff.capacity(); i++) { System.out.print(bbuff.get(i) + " "); } // 將ByteBuffer的數據解碼成字符序列 System.out.println("\n" + cnDecoder.decode(bbuff)); }}
2 回答

嚕嚕噠
TA貢獻1784條經驗 獲得超7個贊
由于使用UTF-8和GBK編碼在把字符CharBuffer轉成ByteBuffer時候分配的字節容量capacity不一樣導致的,如果你設置的編碼是UTF-8,那么在在執行cnEncoder.encode(cbuff),分配字節容量的源碼如下所示:
int n = ( int )(in.remaining() * averageBytesPerChar()); ByteBuffer out = ByteBuffer.allocate(n); |
UTF-8編碼情況下,分配的時候,capacity會比limit大,而GBK下,capacity和limit是一樣大。所以UTF-8情況下,在遍歷字節序列的時候, 會出現溢出,而GBK不會。所以,你在循環遍歷字節序列的時候把判斷條件bbuff.capacity()換成bbuff.limit()就可以了。
添加回答
舉報
0/150
提交
取消