一种新IO流,可以实现对文件的读写操作,效率比IO流高
IO是面向流(Stream)的;NIO是面向通道(Channel)和缓冲区(Buffer)的,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中
FileChannel:文件通道
DatagramChannel:通过 UDP 读写网络中的数据通道。
SocketChannel:通过 TCP 读写网络中的数据
ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel
我们这里主要讲解FileChannel
NIO中的关键Buffer实现有:ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer,分别对应基本数据类型: byte, char, double, float, int, long, short。当然NIO中还有MappedByteBuffer, HeapByteBuffer, DirectByteBuffer等这里先不进行陈述。
容量 (capacity) :表示 Buffer 最大数据容量,缓冲区容量不能为负,并且创建后不能更改。
限制 (limit) :第一个不应该读取或写入的数据的索引,即位于 limit 后的数据不可读写。缓冲区的限制不能为负,并且不能大于其容量。
位置 (position):下一个要读取或写入的数据的索引。缓冲区的位置不能为负,并且不能大于其限制
public static void main(String[] args) throws IOException {
//字节输入流
FileInputStream fileInputStream=new FileInputStream(new File("object02/src/a.txt"));
//字节输出流
FileOutputStream fileOutputStream=new FileOutputStream(new File("object02/src/b.txt"));
//获取通道,通过文件对应io流获取对应通道
FileChannel fromFileChannel=fileInputStream.getChannel();
FileChannel toFileChannel=fileOutputStream.getChannel();
//创建缓冲区并分配空间
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
//读取文件数据到缓冲区
while (fromFileChannel.read(byteBuffer)!=-1){
//设置缓冲区为读模式(看源码)
byteBuffer.flip();
//写数据
toFileChannel.write(byteBuffer);
//清空缓冲区(不清空缓冲区无法进行下一次读取,因为position=capacity,看源码)
byteBuffer.clear();
}
//关闭资源
fileInputStream.close();
fileOutputStream.close();
fromFileChannel.close();
toFileChannel.close();
}
原文:https://www.cnblogs.com/Y-wee/p/13435939.html