ilove581314
ilove581314
2015-10-29 06:02

Java Nio中Charset的decode()方法问题

  • nio charset decode
    try {
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        System.out.println("capacity = " + byteBuffer.capacity() + ", limit = " + byteBuffer.limit() + ", position = " + byteBuffer.position());

        FileChannel channel = new FileInputStream(PATH).getChannel();
        channel.read(byteBuffer);

        System.out.println("capacity = " + byteBuffer.capacity() + ", limit = " + byteBuffer.limit() + ", position = " + byteBuffer.position());
    byteBuffer.clear();
        System.out.println("capacity = " + byteBuffer.capacity() + ", limit = " + byteBuffer.limit() + ", position = " + byteBuffer.position());

        CharBuffer buffer = Charset.defaultCharset().decode(byteBuffer);
        System.out.println("capacity = " + buffer.capacity() + ", limit = " + buffer.limit() + ", position = " + buffer.position());
    } catch (Exception e) {
        e.printStackTrace();
    }

代码如上,假设有一个文件是系统默认GBK编码,文件内容只有一个数字1,那么上述代码在decode之后得到的CharBuffer的容量为什么是21,比原ByteBuffer都大?而且CharBuffer的容量与极限为什么不同?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

0条回答

为你推荐