java-IO-文件通道(FileChannel)

  • FileChannel
  1. 面向文件的通道
  2. 可以从FileInputStreamFileOutputStreamRandomAccessFile中通过getChannel()方法获得
  • FileChannel实现文件复制
// 1、当文件大小小于2GB时,这种方式没有什么大问题,但是如果文件小大超过2GB,这种方式就会数据丢失
// 测试文件大小:8832KB
public static void ioOption() throws IOException {

    // 文件输入流通道
    FileChannel inputChannel = new FileInputStream(new File("D:/demo.txt")).getChannel();
    // 文件输出流通道
    FileChannel outputChannel = new FileOutputStream(new File("D:/copy.txt")).getChannel();
    // 数据转移
    inputChannel.transferTo(0, inputChannel.size(), outputChannel);

    inputChannel.close();
    outputChannel.close();
}
输出:
耗时(毫秒):10

// 2、当文件大小超过2GB时处理办法
// 测试文件大小:8832KB
public static void ioOption() throws IOException {

    // 文件输入流通道
    FileChannel inputChannel = new FileInputStream(new File("D:/demo.txt")).getChannel();
    // 文件输出流通道
    FileChannel outputChannel = new FileOutputStream(new File("D:/copy.txt")).getChannel();

    // 文件转移起始位置,默认0
    long position  = 0;
    // 文件长度
    long size  = inputChannel.size();
    // 数据转移
    // count 转移的字节数
    long count = inputChannel.transferTo(position, size, outputChannel);
    // 循环方式,转移数据
    // 比如:
    // 文件长度为220,但是一次只能转移100;position = 0,size = 220
    // 100 < 220,
    // 第二次从100开始,转移长度为120;position = 100,size = 120
    // 100 < 120,
    // 第三次从200开始,转移长度为20;position = 200,size = 20
    // 20 = 20
    // 退出循环,转移完毕
    while(count < size){
        position += count;
        size -= count;
        count = inputChannel.transferTo(position, size, outputChannel);
    }

    inputChannel.close();
    outputChannel.close();
}
  • 传统IO方式文件复制
// 测试文件大小:8832KB
public static void ioOption4() throws IOException {

    // 获取文件 字节输入流,如果文件不存在抛出异常
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("D:/demo.txt")));
    // 获取文件 字节输出流,如果文件不存在自动创建文件
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/copy.txt")));
    // 字节数组
    byte[] bytes = new byte[1024];

    int len = 0;
    // 一次读取一个 bytes 大小的数据
    // len 表示读取到的字节数,如果没有数据则返回 -1
    while ((len = bis.read(bytes))!= -1){
        bos.write(bytes,0,len);
    }

    bis.close();
    bos.close();
}
输出:
耗时(毫秒):22

 总结:两种实现方式效率大约相差一倍

猜你喜欢

转载自blog.csdn.net/m0_37524661/article/details/87913278