采用合适的IO流提高文件读取效率

现在有网络传输文件的需求,需要先将文件写出到服务器本地磁盘(需求见:https://blog.csdn.net/u014532775/article/details/101306634),采用传统的IO流速度较慢,在这做一个总结,不同场景和文件大小可以使用不同的方式。

1.传统的IO读取方式:

    /**
     * 最传统的方式   40M文件 byte字节1024时平均220ms  byte字节8192时平均时长70ms
     * @throws Exception
     */
    public static void traditionTest() throws Exception{
        FileInputStream inputStream = new FileInputStream(new File("\\home\\www\\source.mp4"));
        FileOutputStream outputStream = new FileOutputStream(new File("\\home\\www\\target.mp4"));
        byte[] bytes = new byte[1024];
        int len;
        while ((len = inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        outputStream.close();
        inputStream.close();
    }

2.使用java8或者commons IO的FileUtils或者guava包下的copy方法:

    /**
     * 使用java8或者commons IO的FileUtils或者guava包下的copy方法  40M文件 80ms左右
     * @throws Exception
     */
    public static void fileUtilTest() throws Exception{
        FileInputStream inputStream = new FileInputStream(new File("\\home\\www\\source.mp4"));
        File out = new File("\\home\\www\\target.mp4");
        Files.copy(inputStream,out.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

3.FileChannel方式:

    /**
     * FileChannel方式  这种是综合效率最高的一种读写方式 40M文件 60ms左右 用到了nio相关知识
     */
    public static void nioTest() throws Exception{
        FileInputStream inputStream = new FileInputStream(new File("\\home\\www\\source.mp4"));
        FileOutputStream outputStream = new FileOutputStream(new File("\\home\\www\\target.mp4"));

        FileChannel in = inputStream.getChannel();
        FileChannel out = outputStream.getChannel();
        in.transferTo(0,in.size(),out);
    }

推荐采用FileChannel方式,传输速度较高

如果输入的是InputStream,处理方式可以参考:https://www.cnblogs.com/asfeixue/p/9065681.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值