public static void main(String[] args) { final String str="IOStudy/src/NIOTest/FileCHannelTest.java"; File file=new File("IOStudy/src/青帝.txt"); try { FileChannel channel=new FileInputStream(file).getChannel(); FileChannel out=new FileOutputStream("test.txt").getChannel(); MappedByteBuffer buffer=channel.map(FileChannel.MapMode.READ_ONLY,0,file.length()); out.write(buffer); buffer.flip(); Charset charset= Charset.forName("GBK"); CharsetDecoder decoder=charset.newDecoder(); CharBuffer charBuffer=decoder.decode(buffer); System.out.print(charBuffer); } catch (Exception e) { e.printStackTrace(); } }
今天學習nio的Charset類,發現當使用decoder.decode方法時,會拋異常。查了api,如開頭的截圖“當輸入的字節數組對於給定的charset是非法的,或者給定的輸入字節數組不是16位的Unicode數組時,就會拋出異常”我理解的意思是,當我把utf8格式的中文轉換成gbk的字符緩沖時,對於gbk,這個utf8字節緩沖三個字節一個漢字,然而gbk是兩個字節一個漢字,因此對於這個gbk來說,這段二進制是不合法的。然后我將內容轉換為英文,就可以順利轉出。所以大概是這個意思。
先記錄下來,以后再有理解再來更正。