javanio读取文件超出问题

29 篇文章 0 订阅

问题:读取一个文件按读取的byte[]输出时输出超出文件内容

问题发生示例: 有文件a.txt,内容为 ‘12345 \n 12345 \n 123’,通过如下代码输出结果为’12345 \n 12345 \n 12312345\n’ 即表现形式是输出超了

public class Demo1 {
    public static void main(String[] args) throws IOException {
        File f = new File("filePath");
        FileInputStream fis = new FileInputStream(f);
        FileChannel channel = fis.getChannel();
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        int i = -1;
        while ((i = channel.read(allocate)) != -1) {
            allocate.flip();
            byte[] array = allocate.array();
            System.out.println(new String(array));
            allocate.clear();
        }
        channel.close();
//        fis.close();
    }
}

原因:调用byteBuffer.clear OR byteBuffer.compact时 byteBuffer内部的byte数组未被初始化,仅仅是重置了状态标识字段

public class Demo1 {
    public static void main(String[] args) throws IOException {
        File f = new File("filePath");
        FileInputStream fis = new FileInputStream(f);
        FileChannel channel = fis.getChannel();
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        int i = -1;
        while ((i = channel.read(allocate)) != -1) {
            allocate.flip();
            byte[] array = allocate.array();
            // -----注意这里 在读取最后一个不完整的byte数组时,获取读取字节数做数组切片
           if (allocate.remaining() != 1024) {
                System.out.println(new String(Arrays.copyOfRange(array, 0, allocate.remaining())));
            } else {
                System.out.println(new String(array));
            }
            // -------------------------------
            allocate.get(array);
            allocate.clear();
        }
        channel.close();
//        fis.close();
    }
}

上面的----夹着的代码也可替换为如下代码

   byte[] buf = new byte[allocate.remaining()];
        allocate.get(buf);

上面最后一行没有关闭fis.close是因为channel.close调用到最后适合fis.close一样的效果,如下图

channel.close

在这里插入图片描述
在这里插入图片描述

fis.close

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值