NIO详解及用(一)
原创1.基本细节
1、传统IO(BIO)
传统IO以流程为导向,是同步阻塞。IO。每次socket请求需要由一个线程处理。如果没有足够的线程可以处理,则请求将等待或被拒绝。也就是说,每个连接都需要服务用一个线程来处理它。这是传统IO效率低下的原因。
2、NIO(NIO 1.0或New IO或 Non Blocking IO)
因为传统IO效率低下JDK1.4更高版本提供了一套API具体操作无阻塞I/O,可替代标准Java IO API。
注:传统I/O该包已被使用。NIO重新实施,即使我们使用传统的IO,也将比原来更高效。
NIO使用事件驱动思维,基于Reactor(本文将解释),何时。socket存在可读或可写的流。socket操作系统将通知引用程序对其进行相应的处理,然后应用程序将流读取到缓冲区或写入操作系统。(不是一个线程处理每个请求,而是一个线程连续轮询每个请求IO运行状态)。
NIO支持面向缓冲区、基于通道IO操作。NIO文件的读取和写入将以更高效的方式执行。由三个主要部分组成: 缓冲区(Buffers),通道(Channels)和选择器(Selector)。 我们将逐一解释。
重要的一句话: NIO和传统IO第一个大的区别,IO以流程为导向,NIO面向缓冲区。
3、AIO(NIO 2.0)
异步非阻塞IO也就是说,没有必要像NIO像一个线程轮询所有IO运行状态改变,在相应的状态改变后,系统会通知对应的线程来处理。
在JDK1.7中,java.nio.channels包下增加了四个异步通道:
- AsynchronousSocketChannel
- AsynchronousServerSocketChannel
- AsynchronousFileChannel
- AsynchronousDatagramChannel
其中的read/write方法,将在读取完成时返回带有回调函数的对象。/写入操作后,直接调用回调函数。
AIO不是本文的重点,只是简单的介绍。
二、NIO三个主要部件的详细说明
1,缓冲区(Buffer )
缓冲区(Buffer) :特定基本数据类型的容器。通过 java.nio 包已定义,所有缓冲区(ByteBuffe、CharBuffer、 ShortBuffer、IntBuffer、LongBuffer、FloatBuffer、DoubleBuffer)都是 Buffer 抽象类的子类。
在NIO在库中,所有数据都用缓冲区处理。读取数据时,它直接读取缓冲区。随时访问NIO中的数据通过缓冲区进行操作。
缓冲区中的四个核心属性:
- capacity:Capacity,表示缓冲区中存储数据的最大容量。一旦语句无法更改。
- limit:bounds,表示可以在缓冲区中操作的数据的大小。(limit无法读取和写入过帐数据)
- position:Location,表示在缓冲区中操作数据的位置。
- mark:标记,指示记录当前position地方可以通过reset()恢复到mark的位置。
注意:0 <= mark <= position <= limit <= capacity
缓冲区实际上是一个数组,提供诸如结构化数据访问和读写位置维护等信息。请参考四个核心属性以查看下图。

缓冲区访问数据的两种核心方法:
- put():将数据存储到缓冲区中。
put(byte b):将给定的单个字节写入缓冲区的当前位置。
put(byte[] src):将 src 中的字节被写入缓冲区的当前位置。
put(int index, byte b):将指定的字节写入缓冲区的索引位置。(不会移动 position)- get():获取缓存中的数据。
get():读取单个字节
get(byte[] dst):批量读取多个字节。 dst 中
get(int index):读取指定索引位置的字节。(不会移动 position)
应了解常用方法:

操作缓冲区的代码如下所示,可以简单地查看以便于理解。我们稍后将使用它。NIO这些代码不会被亲自操纵。
@Test
public void test1(){
String str = "abcd";
//1. 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("-----------------allocate() 创建----------------");
System.out.println("position = "+buf.position());
System.out.println("limit= "+buf.limit());
System.out.println("capacity = "+buf.capacity());
//2. 利用 put() 将数据存储到缓冲区中。
buf.put(str.getBytes());
System.out.println("-----------------put() 存储----------------");
System.out.println("position = "+buf.position());
System.out.println("limit = "+buf.limit());
System.out.println("capacity = "+buf.capacity());
//3. 切换读取数据模式
buf.flip();
System.out.println("-----------------flip()----------------");
System.out.println("position = "+buf.position());
System.out.println("limit = "+buf.limit());
System.out.println("capacity = "+buf.capacity());
//4. 利用 get() 读取缓冲区中的数据。
byte[] dst = new byte[buf.limit()];
buf.get(dst);
System.out.println(new String(dst, 0, dst.length));
System.out.println("-----------------get() 读取----------------");
System.out.println("position = "+buf.position());
System.out.println("limit = "+buf.limit());
System.out.println("capacity = "+buf.capacity());
//5. rewind() : 可重复读
buf.rewind();
System.out.println("-----------------rewind() 可重复读----------------");
System.out.println("position = "+buf.position());
System.out.println("limit = "+buf.limit());
System.out.println("capacity = "+buf.capacity());
//6. clear() : 清空缓冲区. 然而,缓冲区中的数据仍然存在,但处于“遗忘”状态。
buf.clear();
System.out.println("-----------------clear()----------------");
System.out.println("position = "+buf.position());
System.out.println("limit = "+buf.limit());
System.out.println("capacity = "+buf.capacity());
System.out.println((char)buf.get());
}
操作结果如下:
-----------------allocate() 创建----------------
position = 0
limit= 1024
capacity = 1024
-----------------put() 存储----------------
position = 4
limit = 1024
capacity = 1024
-----------------flip()----------------
position = 0
limit = 4
capacity = 1024
abcd
-----------------get() 读取----------------
position = 4
limit = 4
capacity = 1024
-----------------rewind() 可重复读----------------
position = 0
limit = 4
capacity = 1024
-----------------clear()----------------
position = 0
limit = 1024
capacity = 1024
a
mark() : 标记 ,表示记录当前 position 的位置。
reset() : 恢复到 mark 的位置。
关于mark()、reset() 根据下面的代码可以理解的用法。
@Test
public void test2(){
String str = "abcde";
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put(str.getBytes());
buf.flip();
byte[] dst = new byte[buf.limit()];
buf.get(dst, 0, 2);
System.out.println(new String(dst, 0, 2));
System.out.println("position1 = "+buf.position());
//mark() : 标记 position=2
buf.mark();
buf.get(dst, 2, 2);
System.out.println(new String(dst, 2, 2));
System.out.println("position2 = "+buf.position());
//reset() : 恢复到 mark 的位置
buf.reset();
System.out.println("position3 = "+buf.position());
//确定缓冲区中是否剩余任何数据
if(buf.hasRemaining()){
//获取缓冲区中的操作数。
System.out.println(buf.remaining());
}
}
上面的代码很容易理解。如果您理解它,就不需要查看代码实现。当您真正操作时,您不会手动编写这些原则级代码。
NIO缓冲器分为非直接缓冲器和非直接缓冲器。
1.1非直接缓冲区:

当使用非直接缓冲区时,即通过。allocate()方法分配缓冲区并在中建立缓冲区。JVM在内存中,当我们的程序想要从硬盘读取数据时,需要以下三个步骤:
1.首先将数据从物理硬盘读取到物理内存中。
2然后复制内容JVM的内存中
3然后,读取应用程序可以读取内容。
阅读和写作都是这样,这需要复制这个动作。缺点是 速度慢 ,优点是 安全 。
代码如下:
/**
* 非直接缓冲区 读写操作
* @throws IOException
*/
@Test
public void test001() throws IOException {
long statTime=System.currentTimeMillis();
// 读入流
FileInputStream fst = new FileInputStream("f://1.mp4");
// 写入流
FileOutputStream fos = new FileOutputStream("f://2.mp4");
// 创建通道
FileChannel inChannel = fst.getChannel();
FileChannel outChannel = fos.getChannel();
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
while (inChannel.read(buf) != -1) {
// 打开读取模式
buf.flip();
// 将数据写入通道
outChannel.write(buf);
buf.clear();
}
// 关闭通道 ,关闭连接
inChannel.close();
outChannel.close();
fos.close();
fst.close();
long endTime=System.currentTimeMillis();
System.out.println("非直接缓冲区的操作需要时间。:"+(endTime-statTime));
}
1.2直接缓冲区:

使用直接缓冲区是在物理内存中直接在应用程序和物理磁盘中创建缓冲区。,这将省略复制步骤。(allocateDirect()方法分配直接缓冲区以在物理内存中构建缓冲区)
/**
* 直接缓冲区
* @throws IOException
*/
@Test
public void test002() throws IOException {
long statTime=System.currentTimeMillis();
//创建管道
FileChannel inChannel= FileChannel.open(Paths.get("f://1.mp4"), StandardOpenOption.READ);
FileChannel outChannel=FileChannel.open(Paths.get("f://2.mp4"), StandardOpenOption.READ,StandardOpenOption.WRITE, StandardOpenOption.CREATE);
//定义映射文件。
MappedByteBuffer inMappedByte = inChannel.map(MapMode.READ_ONLY,0, inChannel.size());
MappedByteBuffer outMappedByte = outChannel.map(MapMode.READ_WRITE,0, inChannel.size());
//直接操作缓冲器
byte[] dsf=new byte[inMappedByte.limit()];
inMappedByte.get(dsf);
outMappedByte.put(dsf);
inChannel.close();
outChannel.close();
long endTime=System.currentTimeMillis();
System.out.println("操作直接缓冲需要时间:"+(endTime-statTime));
}
2、通道(Channel)
Channel表示内存。IO设备的连接(例如文件、套接字),即源节点和目标节点之间的连接。在里面java NIO中Channel它本身不负责存储和访问数据数据,主要使用缓冲区(buffer),负责数据传输。
要给出一个生动而明显的例子来说明操作系统中通道的必要性,请先看下图:

如果我们使用传统io,也就是说,不要使用信道进行数据传输,那么我们cpu将负责直接致电io接口,然后是直接缓冲区。/非直接缓冲相互作用。
如果我们在需要时使用频道。I/O操作时,cpu只需启动频道,然后cpu您可以继续执行自己的程序,频道执行频道程序,也就是说。 频道造就主持人(CPU和内存)I/O操作之间的并行度更高 。
通道内部运行图如下:

通道的相关方法和代码如下(或那句话,理解,这些都是在应用时内部实现的):
/*
* 一、通道(Channel):用于源节点和目标节点之间的连接。在里面java NIO负责缓冲区中的数据传输。Channel它本身不存储数据,需要使用缓冲区传输。
*
* 2.通道的主要实现类。
* java.nio.channels.Channel 接口:
* |--FileChannel:用于读取、写入、映射和操作文件的通道。
* |--SocketChannel:通过 TCP 在网络中读取和写入数据。
* |--ServerSocketChannel:可以监控新进入者 TCP 连接,为每个新的传入连接创建一个连接。 SocketChannel。
* |--DatagramChannel:通过 UDP 读写网络中的数据通道。
*
* 3.接入通道
* 1.java对于提供了支持通道的类。getChannel()方法
* 本地IO:
* FileInputStream/FileOutputStream
* RandomAccessFile
*
* 网络IO:
* Socket
* ServerSocket
* DatagramSocket
*
* 2.在JDK 1.7 中的NIO.2 为每个通道提供了静态方法。 open()
* 3.在JDK 1.7 中的NIO.2 的Files工具类的newByteChannel()
*
* 4.通道之间的数据传输
* transferFrom()
* transferTo()
*
* 五、分散(Scatter)与聚集(Gather)
* 分散读取(Scattering Reads):将通道中的数据扩展到多个缓冲区。
* 聚合写入(Gathering Writes):将数据从多个缓冲区聚合到通道中
*
* 6.字符集:Charset
* 编码:字符串-“”字符数组
* 解码:字符数组-》字符串
*/
public class TestChannel {
//使用通道复制文件(非直接缓冲区)
@Test
public void test1(){
long start=System.currentTimeMillis();
FileInputStream fis=null;
FileOutputStream fos=null;
FileChannel inChannel=null;
FileChannel outChannel=null;
try{
fis=new FileInputStream("d:/1.avi");
fos=new FileOutputStream("d:/2.avi");
//1.获取通道
inChannel=fis.getChannel();
outChannel=fos.getChannel();
//2.分配指定大小的缓冲区
ByteBuffer buf=ByteBuffer.allocate(1024);
//3.将通道中的数据存储在缓冲区中。
while(inChannel.read(buf)!=-1){
buf.flip();//切换读取数据的模式
//4.将缓冲区中的数据写入通道。
outChannel.write(buf);
buf.clear();//清空缓冲区
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(outChannel!=null){
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inChannel!=null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
long end=System.currentTimeMillis();
System.out.println("耗时:"+(end-start));//耗时:1094
}
//使用直接缓冲区复制文件(内存映射文件)
@Test
public void test2() {
long start=System.currentTimeMillis();
FileChannel inChannel=null;
FileChannel outChannel=null;
try {
inChannel = FileChannel.open(Paths.get("d:/1.avi"), StandardOpenOption.READ);
outChannel=FileChannel.open(Paths.get("d:/2.avi"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
//内存映射文件
MappedByteBuffer inMappedBuf=inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMappedBuf=outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
//直接向缓冲区读取和写入数据。
byte[] dst=new byte[inMappedBuf.limit()];
inMappedBuf.get(dst);
outMappedBuf.put(dst);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(outChannel!=null){
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inChannel!=null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
long end=System.currentTimeMillis();
System.out.println("消耗的时间为:"+(end-start));//消耗的时间为:200
}
//通道之间的数据传输(直接缓冲区)
@Test
public void test3(){
long start=System.currentTimeMillis();
FileChannel inChannel=null;
FileChannel outChannel=null;
try {
inChannel = FileChannel.open(Paths.get("d:/1.avi"), StandardOpenOption.READ);
outChannel=FileChannel.open(Paths.get("d:/2.avi"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
inChannel.transferTo(0, inChannel.size(), outChannel);
outChannel.transferFrom(inChannel, 0, inChannel.size());
} catch (IOException e) {
e.printStackTrace();
}finally{
if(outChannel!=null){
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inChannel!=null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
long end=System.currentTimeMillis();
System.out.println("消耗的时间为:"+(end-start));//消耗的时间为:147
}
//分散和聚集
@Test
public void test4(){
RandomAccessFile raf1=null;
FileChannel channel1=null;
RandomAccessFile raf2=null;
FileChannel channel2=null;
try {
raf1=new RandomAccessFile("1.txt","rw");
//1.获取通道
channel1=raf1.getChannel();
//2.分配指定大小的缓冲区
ByteBuffer buf1=ByteBuffer.allocate(100);
ByteBuffer buf2=ByteBuffer.allocate(1024);
//3.分散读取
ByteBuffer[] bufs={buf1,buf2};
channel1.read(bufs);
for(ByteBuffer byteBuffer : bufs){
byteBuffer.flip();
}
System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
System.out.println("--------------------");
System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));
//4.聚集写入
raf2=new RandomAccessFile("2.txt", "rw");
channel2=raf2.getChannel();
channel2.write(bufs);
}catch (IOException e) {
e.printStackTrace();
}finally{
if(channel2!=null){
try {
channel2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(channel1!=null){
try {
channel1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raf2!=null){
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raf1!=null){
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//输出支持的字符集
@Test
public void test5(){
Map map=Charset.availableCharsets();
Set> set=map.entrySet();
for(Entry entry:set){
System.out.println(entry.getKey()+"="+entry.getValue());
}
}
//字符集
@Test
public void test6(){
Charset cs1=Charset.forName("GBK");
//获取编码器
CharsetEncoder ce=cs1.newEncoder();
//获取解码器
CharsetDecoder cd=cs1.newDecoder();
CharBuffer cBuf=CharBuffer.allocate(1024);
cBuf.put("哈哈哈");
cBuf.flip();
//编码
ByteBuffer bBuf=null;
try {
bBuf = ce.encode(cBuf);
} catch (CharacterCodingException e) {
e.printStackTrace();
}
for(int i=0;i<12;i++){
System.out.println(bBuf.get());//-64-78-64-78-71-2-7-2-80-55-80-55
}
//解码
bBuf.flip();
CharBuffer cBuf2=null;
try {
cBuf2 = cd.decode(bBuf);
} catch (CharacterCodingException e) {
e.printStackTrace();
}
System.out.println(cBuf2.toString());
}
}
3,选择器(Selector)
Selector负责监控渠道。IO状态,也可以称为多路复用器。 。它是Java NIO用于检查一个或多个的核心组件之一NIO Channel(通道)的状态是否可读写。这允许对多个channels,也就是说,可以管理多个网络链接。
示例代码(理解它,它是打包的,您不需要自己编写):
/*
* 一、使用NIO 完成网络通信的三个核心:
*
* 1、通道(Channel):负责连接
* java.nio.channels.Channel 接口:
* |--SelectableChannel
* |--SocketChannel
* |--ServerSocketChannel
* |--DatagramChannel
*
* |--Pipe.SinkChannel
* |--Pipe.SourceChannel
*
* 2.缓冲区(Buffer):负责数据访问
*
* 3.选择器(Selector):是 SelectableChannel 多路复用器的。用于监控SelectableChannel的IO状况
*/
public class TestBlockingNIO {//没用Selector,阻塞类型
//客户端
@Test
public void client() throws IOException{
SocketChannel sChannel=SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
FileChannel inChannel=FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
ByteBuffer buf=ByteBuffer.allocate(1024);
while(inChannel.read(buf)!=-1){
buf.flip();
sChannel.write(buf);
buf.clear();
}
sChannel.shutdownOutput();//关闭发送通道,表示发送完成。
//接收服务方的反馈
int len=0;
while((len=sChannel.read(buf))!=-1){
buf.flip();
System.out.println(new String(buf.array(),0,len));
buf.clear();
}
inChannel.close();
sChannel.close();
}
//服务端
@Test
public void server() throws IOException{
ServerSocketChannel ssChannel=ServerSocketChannel.open();
FileChannel outChannel=FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
ssChannel.bind(new InetSocketAddress(9898));
SocketChannel sChannel=ssChannel.accept();
ByteBuffer buf=ByteBuffer.allocate(1024);
while(sChannel.read(buf)!=-1){
buf.flip();
outChannel.write(buf);
buf.clear();
}
//向客户发送反馈
buf.put("服务器成功接收数据".getBytes());
buf.flip();//为读取模式提供
sChannel.write(buf);
sChannel.close();
outChannel.close();
ssChannel.close();
}
}
SelectionKey
SelectionKey:表示通道和选择器之间的注册关系。每次向选择器注册频道时,都会选择一个事件。(选择键)选择键包含两组表示为整数值的操作。操作集的每个位表示键的通道支持的一类可选操作。
例如:呼叫 register(Selector sel, int ops) 向选择器注册通道时,选择器侦听通道事件,该事件需要传递第二个参数。 ops 指定。
ops表示可以侦听的事件类型()。 SelectionKey 四个常数):
读 : SelectionKey.OP_READ (1)
写 : SelectionKey.OP_WRITE (4)
连接 : SelectionKey.OP_CONNECT (8)
接收 : SelectionKey.OP_ACCEPT (16)
如果在注册时侦听多个事件,则可以使用“bit or”运算符进行连接。
示例代码(刚刚知道):
public class TestNonBlockingNIO {
//客户端
@Test
public void client()throws IOException{
//1.获取通道
SocketChannel sChannel=SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
//2.切换非阻塞模式
sChannel.configureBlocking(false);
//3.分配指定大小的缓冲区
ByteBuffer buf=ByteBuffer.allocate(1024);
//4.将数据发送到服务器
Scanner scan=new Scanner(System.in);
while(scan.hasNext()){
String str=scan.next();
buf.put((new Date().toString()+"
"+str).getBytes()); buf.flip(); sChannel.write(buf); buf.clear(); } //5.关闭通道 sChannel.close(); }
//服务端
@Test
public void server() throws IOException{
//1.获取通道
ServerSocketChannel ssChannel=ServerSocketChannel.open();
//2.切换非阻塞模式
ssChannel.configureBlocking(false);
//3.绑定连接
ssChannel.bind(new InetSocketAddress(9898));
//4.获取选择器
Selector selector=Selector.open();
//5.将频道注册到选择器并指定“侦听接收到的事件”
ssChannel.register(selector,SelectionKey.OP_ACCEPT);
//6.选择器上的轮询样式就绪事件。
while(selector.select()>0){
//7.获取当前选择器中所有已注册的“选择键(准备收听事件)”
Iterator it=selector.selectedKeys().iterator();
while(it.hasNext()){
//8.为“就绪”活动做好准备。
SelectionKey sk=it.next();
//9.确定何时准备好。
if(sk.isAcceptable()){
//10.如果“接收就绪”,则获取客户端连接。
SocketChannel sChannel=ssChannel.accept();
//11.切换非阻塞模式
sChannel.configureBlocking(false);
//12.在选择器上注册通道
sChannel.register(selector, SelectionKey.OP_READ);
}else if(sk.isReadable()){
//13.获取当前选择器上处于Read Ready状态的通道。
SocketChannel sChannel=(SocketChannel)sk.channel();
//14.读取数据
ByteBuffer buf=ByteBuffer.allocate(1024);
int len=0;
while((len=sChannel.read(buf))>0){
buf.flip();
System.out.println(new String(buf.array(),0,len));
buf.clear();
}
}
//15.取消选择键SelectionKey
it.remove();
}
}
}
} 版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123




