java NIO /IO 非阻塞IO 和IO的区别及代码示例

来源:互联网 发布:国外必备软件 编辑:程序博客网 时间:2024/05/21 17:17
NIO与IO最大的区别之处是:
(1)处理数据的方式不同,IO是以流的方式来处理数据的,每次操作只处理一个字节,因此处理的效率比较低;而NIO是以块的方式来处理数据的,每次操作都是以块为单位处理的,因此处理的效率比IO高很多。
(2)NIO把大多数消耗时间的IO操作交给操作系统来完成,因此性能相对IO有很大的提升。
(3)在NIO中所有的数据处理都是以buffer进行的,当写入数据的时候,首先是向buffer中写入,而数据被读取的时候也是先被保存到buffer中。而原来的IO系统中,数据的读取是通过Stream流的方式。
 其实还有一点就是:java NIO 非堵塞技术实际是采用了观察者模式(Observer)来为我们监视I/O端口,若有内容进来,就会自动通 知我们,这样我们就不必一直等待,从而实现了流畅的读写,也就不堵塞了。而Java IO技术在打开一个IO通道后,将一直等待在端口一边读取字节内容,如果没有内容进来,也要一直等待,这样会影响程序的性能。
  综合上述比较:可以很清晰的看到NIO在读取数据的效率上比IO有明显的提升。

代码示例:
IO例子:
public class DemoIo {
public static final String File="D:/home/RECORD_10000000.txt";
private static void getProperty() throws FileNotFoundException, IOException {
FileInputStream in=new FileInputStream(File);
byte[] buffer =new byte[1024*1024*50];//50MB
while (true) {
int r = in.read(buffer);
if (r == -1) {
break;
}
}
}
public static void main(String[] args) throws IOException {
long startTime=System.currentTimeMillis();
getProperty();
System.out.println("-----endTime-startTime======="+(System.currentTimeMillis()-startTime));
}


NIO例子:
public class DemoNio {
 
public static final String File="D:/home/RECORD_10000000.txt";
 
private static void getProperty() throws FileNotFoundException, IOException {
FileInputStream in=new FileInputStream(File);
FileChannel channel=in.getChannel();
//每次读取50MB到缓冲区      (本机最大每次读取58MB)
ByteBuffer buffer=ByteBuffer.allocate(1024*1024*50);
while(true){
// clear方法重设缓冲区,使它可以接受读入的数据
buffer.clear();
// 从输入通道中将数据读到缓冲区
    int r=channel.read(buffer);
    if(r==-1){
     break;
    }
}
}
public static void main(String[] args) throws IOException {
long startTime=System.currentTimeMillis();
getProperty();
System.out.println("-----endTime-startTime======="+(System.currentTimeMillis()-startTime));
}
}



原创粉丝点击