看动画,学JavaNIO教程17:如何使用 FileChannel 写数据?

看动画,学JavaNIO教程17:如何使用 FileChannel 写数据?
前面我们学习了
如何使用 FileChannel 读数据
这一节
我们来学习如何使用 FileChannel 写数据
写数据需要用到 write 方法
一共有 4 个
功能如图所示
都是通过 Channel 将缓冲区中的数据写入文件
那这么多方法
哪一个更常用呢
从方法使用率来看
第一个方法更常用
方法需指定一个缓冲区
将这个缓冲区里的数据写到文件中
方法返回一个 int 类型的值
表示写了多少个字节
接下来
用它来编写一个示例
【注】请观看视频查看具体内容

观看视频

方法描述
方法使用率

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/124600059
今日推荐