码迷,mamicode.com
首页 > 编程语言 > 详细

Java NIO学习-详细内容

时间:2015-10-14 19:33:31      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:

一、三大类

  1、Channels

  2、Selector与SelectionKey

  3、Buffer及其子类

  说明:所有的Channel都需要和Buffer类结合使用,通过Buffer类实现缓冲区

     直接通过Channels即可实现同步非阻塞io,SelectableChannel类configureBlocking(boolean block)方法配置是否阻塞,false不阻塞,默认true.(由上图可知,FileChannel是不能配置阻塞非阻塞的,因为直接通过系统IO读到文件,不会有阻塞和非阻塞的区分)

     通过Selector与SelectionKey可以实现IO多路复用

  nio包结构:

  技术分享

  nio包接口:

  技术分享

  Channels类说明:

  主要负责把InputStream和OutputStream转为Channel,把Channel转为InputStream、OutputStream、Reader、Writer,经典IO与NIO互相转换

       static ReadableByteChannel newChannel(InputStream in) 
    static WritableByteChannel newChannel(OutputStream out) 
    static InputStream newInputStream(ReadableByteChannel ch) 
    static OutputStream newOutputStream(WritableByteChannel ch) 
    static Reader newReader(ReadableByteChannel ch, CharsetDecoder dec, int minBufferCap) 
    static Reader newReader(ReadableByteChannel ch, String csName) 
    static Writer newWriter(WritableByteChannel ch, CharsetEncoder enc, int minBufferCap) 
    static Writer newWriter(WritableByteChannel ch, String csName)

  接口说明

  Channel接口:void close();boolean isOpen()

  ReadableByteChannel接口:int read(ByteBuffer dst)

  WritableByteChannel接口:int write(ByteBuffer src) 

  ByteChannel接口:实现了以上所有接口的接口

  ScatteringByteChannel接口:long read(ByteBuffer[] dsts);long read(ByteBuffer[] dsts, int offset, int length) 。读取一个网络协议的不同部分时有用,如http协议的header和body。

        分散 读取操作可在单个调用中将一个字节序列读入一个或多个给定的缓冲区序列。分散读取通常在实现网络协议或文件格式时很有用,例如将数据分组放入段中(这些段由一个或多个长度固定的头,后跟长度可变的正文组成)。

  GatheringByteChannel接口:long write(ByteBuffer[] srcs) ;long write(ByteBuffer[] srcs, int offset, int length)

        集中 写入操作可在单个调用中写入来自一个或多个给定缓冲区序列的字节序列。集中写入通常在实现网络协议或文件格式时很有用,例如将数据分组放入段中(这些段由一个或多个长度固定的头,后跟长度可变的正文组成)。
  InterruptibleChannel接口:void close()。可被异步关闭和中断的通道。 也可使用线程的interrupt方法来关闭。调用close与调用interrupt都将引发Exception,Exception不同,参看api文档。

Java NIO学习-详细内容

标签:

原文地址:http://www.cnblogs.com/guangshan/p/4878231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!