5.FileChannel

FileChannel只能工作在阻塞模式

获取FileChannel的方法:

1.通过FileInputStream获取channel只能读。

2.通过FileOutStream获取channel只能写。

3.通过RandomAccessFile是否能读写根据构造RandomAccessFile时的读写模式决定。

4.channel关闭调用close方法,不过调用FileInputStream,FileOutputStream或者RandomAccessFIle的close方法会间接调用channel的close方法

/**
     * 基于FileChannel对文件内容进行传输
     * 效率高,比文件流输入输出的形式高
     * 只要调用了transferTo方法,其底层会使用零拷贝进行优化
     * 一次最多传2G数据,大文件可以分多次传输
     */
    public static void channelFileTransfer() {
        try (FileChannel channel = new FileInputStream("text.txt").getChannel();
             FileChannel channel2 = new FileOutputStream(("2.txt")).getChannel()) {
            channel.transferTo(0, channel.size(), channel2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 超过2G文件,分多次传输
     */
    public static void channelFileTransferBigFile() {
        try (FileChannel channel1 = new FileInputStream("text.txt").getChannel();
            FileChannel channel2 = new FileOutputStream("2.txt").getChannel()) {
            //left表示剩余多少字节没有传输
            long totalSize = channel1.size();
            for (long left = totalSize; left > 0; ) {
                long actualSize = channel1.transferTo((totalSize - left), left, channel2);
                left -= actualSize;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

相关推荐

  1. 5.FileChannel

    2024-03-31 14:06:04       13 阅读
  2. FileChannel的使用

    2024-03-31 14:06:04       6 阅读
  3. git-<span style='color:red;'>5</span>

    git-5

    2024-03-31 14:06:04      31 阅读
  4. Webpack5

    2024-03-31 14:06:04       38 阅读
  5. CSS-5

    2024-03-31 14:06:04       35 阅读
  6. DevOps(5)

    2024-03-31 14:06:04       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-31 14:06:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-31 14:06:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-31 14:06:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-31 14:06:04       20 阅读

热门阅读

  1. ospf配置静态路由实验

    2024-03-31 14:06:04       17 阅读
  2. 数据结构--合并区间

    2024-03-31 14:06:04       16 阅读
  3. js关于数组的方法

    2024-03-31 14:06:04       17 阅读
  4. C#面:虚函数和抽象函数的区别

    2024-03-31 14:06:04       15 阅读