
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来说,这段二进制是不合法的。然后我将内容转换为英文,就可以顺利转出。所以大概是这个意思。
先记录下来,以后再有理解再来更正。