阻塞I/O的概念:
非阻塞I/O的概念:
Java中的NIO:
NIO主要有三大核心部分:Channel(通道)、Buffer(缓冲区)、Selector。传统IO是基于字节流和字符流进行操作。而NIO基于Channel和Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者是从缓冲区写入到通道中。Selector(选择区)用于监听多个通道的事件 (比如:连接打开、数据到达)。因此,单个线程可以监听多个数据通道。
一个小demo如下:
public static void method1(){
RandomAccessFile aFile = null;
try{
aFile = new RandomAccessFile("src/nio.txt","rw");
FileChannel fileChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
int bytesRead = fileChannel.read(buf);
System.out.println(bytesRead);
while(bytesRead != -1)
{
buf.flip();
while(buf.hasRemaining())
{
System.out.print((char)buf.get());
}
buf.compact();
bytesRead = fileChannel.read(buf);
}
}catch (IOException e){
e.printStackTrace();
}finally{
try{
if(aFile != null){
aFile.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}