NIO

BIO与NIO

BIO同步阻塞,在调用read方法则会阻塞当前线程等待(从主存中DMA copy至内核缓冲区,然后利用cpu将内核缓冲区的数据读取至进程缓冲区)
NIO过程一致,但是BIO需要一个线程监听一次读写状态,而NIO利用channal通道的概念,利用一个线程监听所有的通道(不断的自旋调用select(),查询是否可以读取),只要通道read完成,再通知读取线程读取

BIO读写文件

public void test(){
	 BufferedInputStream bf=new BufferedInputStream(new FileInputStream(new File("D://test.txt")));
     BufferedOutputStream ot=new BufferedOutputStream(new FileOutputStream(new File("")));
     int i=-1;
     while((i=bf.read())!=-1){
         ot.write(i);
     }
     bf.close();
     ot.close();
}

NIO读写文件

	FileInputStream fi=new FileInputStream(new File(""));
    FileChannel channel = fi.getChannel();
    FileOutputStream fo=new FileOutputStream(new File(""));
    FileChannel channel1 = fo.getChannel();
    ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
    int length=-1;
    int outLength=0;
    while((length=channel.read(byteBuffer))!=-1){
        byteBuffer.flip();
        outLength=0;
        while((outLength=channel1.write(byteBuffer))!=0){
            channel1.write(byteBuffer);
        }
        byteBuffer.clear();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值