看动画,学JavaNIO教程18:如何使用 FileChannel 复制文件?

看动画,学JavaNIO教程18:如何使用 FileChannel 复制文件?
前面我们学习了
如何使用 FileChannel 读写数据
这一节
我们来学习如何使用 FileChannel 复制文件
准备一个要复制的源文件
和负责读数据的 Channel
以及存储数据的缓冲区
当数据通过 Channel 读到缓冲区里以后
我们还需要一个
负责将数据从缓冲区里
写到另一个文件中的 Channel
通过它
将缓冲区里的数据
写到另一个文件中
以上
就是通过 Channel 完成复制文件的过程
【注】请观看视频查看具体内容

观看视频

复制流程图

package main;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author 【看动画,学Java】https://student-api.iyincaishijiao.com/t/Nqrff3f/
 * @author 【官方网站】gorhaf.com
 * @author 【微信公众号】gorhaf
 * @author 【个人微信号】gorhafapp
 * @author 【抖音】人人都是程序员
 * @author 【B站】人人都是程序员
 */
public class Main {
    
    

    public static void main(String[] args) {
    
    
        // 文件路径
        Path src = Paths.get("/Users/admin/Downloads/人人都是程序员.txt");
        Path dst = Paths.get("/Users/admin/Downloads/人人都是程序员副本.txt");
        try {
    
    
            // 创建文件通道
            FileChannel in = FileChannel.open(src, StandardOpenOption.READ);
            FileChannel out = FileChannel.open(dst, StandardOpenOption.CREATE,
                    StandardOpenOption.WRITE);
            // 创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 循环读取字节
            while (in.read(buffer) >= 0 || buffer.position() != 0) {
    
    
                // 翻转缓冲区
                buffer.flip();
                // 写数据
                out.write(buffer);
                // 压缩缓冲区
                buffer.compact();
            }
            // 关闭通道
            in.close();
            out.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

视频全集

其他教程

代码

猜你喜欢

转载自blog.csdn.net/gorhaf/article/details/124602184
今日推荐