nio/io 拷贝文件

nio的拷贝文件大概能比io拷贝文件快1倍左右,为何会快1倍了,查看了它的源码,发现它用到了直接内存,即与jvm内存相比,省去了一次拷贝。所以能加快速度,但它也是一把双刃剑,有如下缺点,可以不借用cpu,是独立的处理器,专门用于处理io

①,申请内存空间比较慢

②,直接内存不属于jvm管理范围内,释放比较难,可能会造成oom问题,出现问题比较难排查

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * @author hui
 * @date 2019/6/12
 */
public class IOUtil {

    public static void fileCopyWithFileChannel( FileInputStream fileInputStream,FileOutputStream fileOutputStream) {
        FileChannel fileChannelInput = null;
        FileChannel fileChannelOutput = null;
        try {
            // 得到fileInputStream的文件通道
            fileChannelInput = fileInputStream.getChannel();
            // 得到fileOutputStream的文件通道
            fileChannelOutput = fileOutputStream.getChannel();
            // 将fileChannelInput通道的数据,写入到fileChannelOutput通道
            fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 用filechannel进行文件复制
     *
     * @param fromFile
     *            源文件
     * @param toFile
     *            目标文件
     */
    public static void fileCopyWithFileChannel(File fromFile, File toFile) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream=new FileInputStream(fromFile);
            fileOutputStream=new FileOutputStream(toFile);
            fileCopyWithFileChannel(fileInputStream, fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            IOUtil.close(fileOutputStream);
            IOUtil.close(fileInputStream);
        }

    }

  public static long copy(final InputStream input, final OutputStream output)
            throws IOException {
        byte[] buffer = new byte[1024];
        long count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    public static void close(Closeable closeable){
        if(closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
        }
    }

}

普通的流的拷贝

 

参考:https://blog.csdn.net/stalin_/article/details/80352132

转载于:https://my.oschina.net/u/3574106/blog/3061288

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值