代码:
// 导入必要的类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
// 定义名为 Copy 的公共类
public class Copy {
// 主方法,程序的入口点,可能抛出异常
public static void main(String[] args) throws Exception {
// 创建输入文件通道,读取 Copy.java 文件
FileChannel in = new FileInputStream("./Test_NIO/src/Copy.java").getChannel();
// 创建输出文件通道,写入 1.txt 文件
FileChannel out = new FileOutputStream("./Test_NIO/src/1.txt").getChannel();
// 创建 ByteBuffer 对象,用于存储读取的数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 循环从输入通道读取数据到缓冲区,直到读取完毕
while (in.read(buffer) != -1) {
// 重置缓冲区的位置和限制,为写入数据做准备
buffer.flip();
// 将缓冲区的数据写入输出通道
out.write(buffer);
// 清空缓冲区,为下一次读取数据做准备
buffer.clear();
}
// 将缓冲区的位置重置为0,以便后续读取缓冲区中的数据
buffer.rewind();
// 循环输出缓冲区中的数据到控制台
while (buffer.hasRemaining())
System.out.print((char) buffer.get());
// 关闭输入和输出通道
in.close();
out.close();
}
}
完美解释了Channel(通道)与 Buffer(缓冲器) 的关系!,in和out的关系!