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

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

  • 相关阅读:
    msyql多个or,and,
    mysql中 where in 用法详解
    history.back(-1)和history.go(-1)的区别
    经典 mysql 28道题
    企业案例(二):增量恢复案例
    企业案例(一):由于mysql sleep线程过多小故障
    mysql数据库恢复
    binlog介绍
    mysql 数据库备份
    docker入门与实践
  • 原文地址:https://www.cnblogs.com/tomato190/p/12659011.html
Copyright © 2011-2022 走看看