zoukankan      html  css  js  c++  java
  • Java NIO 报java.nio.charset.MalformedInputException: Input length = 1异常

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

    先记录下来,以后再有理解再来更正。

  • 相关阅读:
    Postgres的TOAST技术
    Postgresql 分区表 一
    Postgresql 用户管理
    Linux FIO
    haproxy
    RHEL7/CentOS7 Network Service开机无法启动的解决方法
    Cockroachdb 四、用户管理及授权
    Cockroachdb 三、副本设置
    Cockroachdb 二、手动部署
    Cockroachdb 一、系统环境
  • 原文地址:https://www.cnblogs.com/tomato190/p/12659011.html
Copyright © 2011-2022 走看看