一 channel
1.1 channel概念
流的读写通常是单向的。通道是双向的,可以用于读、写和同时读写操作,通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。从通道读取数据到缓冲区,从缓冲区写入数据到通道

1.2 channel与传统对象的区别
1、Channel可以直接将指定文件的部分或全部直接映射成Buffer。
2、程序不能直接访问Channel中的数据,包括读、写入都不行,Channel只能与Buffer进行交互。也就是说, 如果要从Channel中取得数据,必须先用Buffer从Channel中取出一些数据,然后让程序从Buffer中取出这些 数据;如果要将程序中的数据写入Channel,一样先让程序将谁放入Buffer中,程序再将Buffer里的数据写入Channel中。
二 channel的操作案例
1.fromFileChannel
将d盘的内容复制到e盘
RandomAccessFile fromFile = new RandomAccessFile("d:/testbuffer.txt", "rw");
FileChannel fromFileChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("E:/liu.txt", "rw");
FileChannel toFileChannel = toFile.getChannel();
long position = 0;
long count = fromFileChannel.size();
toFileChannel.transferFrom(fromFileChannel, position, count);
2.transferTo
public static void fileChannel() throws Exception {
RandomAccessFile fromFile = new RandomAccessFile("d:/testbuffer.txt", "rw");
FileChannel fromFileChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("E:/li.txt", "rw");
FileChannel toFileChannel = toFile.getChannel();
long position = 0;
long count = fromFileChannel.size();
//toFileChannel.transferFrom(fromFileChannel, position, count);//将d盘内容复制到e盘
fromFileChannel.transferTo(position, count, toFileChannel);//将d盘内容复制到e盘
}
本文介绍了Java NIO中的Channel概念,强调其双向读写特性,并对比了它与传统对象的区别。通过示例展示了如何使用FileChannel进行文件内容的复制,包括`transferFrom`和`transferTo`方法的运用,帮助理解Channel与Buffer的交互操作。
1万+

被折叠的 条评论
为什么被折叠?



