java IO(二): java NIO

java NIO用来解决传统IO的问题,NIO使用的就是多路复用IO设计模式,有几个关键的概念:

(1)Buffer:

Buffer称之为缓冲区,NIO中读写都依赖于缓冲区,其基本类为Buffer类。

(2)Channel:

顾名思义:“通道”,在NIO中,流的操作要基于channel上,而利用channel进行读写操作的数据只能放到Buffer中去,channel提供了双向的操作,既能读也能写。

常用的几种通道:

FileChannel

SocketChanel

ServerSocketChannel

DatagramChannel

以下是利用NIO读写文档的实现代码

 写文件:

//文件写入
                File file = new File("liIo.txt");
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		String str = "nihao,ljyll122";
		buffer.put(str.getBytes());
		buffer.flip();
		
		FileOutputStream outputStream = new FileOutputStream(file);
		FileChannel channel = outputStream.getChannel();
		channel.write(buffer);
				
		channel.close();
		outputStream.close();

 文件读取:

//文件读取
                File file = new File("liIo.txt");
		FileInputStream inputStream = new FileInputStream(file);
		FileChannel channel2 = inputStream.getChannel();
		
		ByteBuffer buffer2 = ByteBuffer.allocate(1024);
		channel2.read(buffer2);
		buffer2.flip();
		
		inputStream.close();
		channel2.close();

(3)Selector:

selector就是用来判断哪个channel有事件发生。


总而言之,Channel相当于道路,Buffer相当于运输车,Selector相当于交通指挥官。

那上述写文件的例子做比方,文件写入相当于送货,首先需要用Buffer将内容装载(put方法),然后在相应的Channel上进行运输(write方法),至于什么时候运输,则由Selector进行决定。当然,Buferr的操作也有讲究,比如说在channelread之前要调用flip()。下面继续。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值