欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java IO(二): java NIO,

来源: javaer 分享于  点击 41498 次 点评:87

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()。下面继续。


相关文章

    暂无相关文章
相关栏目:

用户点评