编程小贴士

给你的编程提供小点子


JAVA中的NIO基础学习

在JDK1.4以前,I/O输入输出处理,我们把它称为旧I/O处理,在JDK1.4开始,java提供了一系列改进的输入/输出新特性,这些功能被称为新I/O(NEW I/O),新添了许多用于处理输入/输出的类,这些类都被放在strong>java.nio包及子包下,并且对原java.io包中的很多类以NIO为基础进行了改写,新添了满足新I/O的功能。

Java NIO和IO的主要区别

IO NIO
面向流
面向缓冲
阻塞IO
 非阻塞IO
选择器

面向缓冲(Buffer)

在整个Java的心I/O中,所以操作都是以缓冲区进行的,使操作的性能大大提高。

操作

在Buffer中存在一系列的状态变量,这状态变量随着写入或读取都可能会被概念,在缓冲区开元使用是三个值表示缓冲区的状态。

  • position:表示下个缓冲区读取或写入的操作指针,没向缓冲区中华写入数据的时候 此指针就会改变,指针永远放在写入的最后一个元素之后。即:如果写入了4个位置的数据,则posotion会指向第5个位置。
  • Limit:表示还有多少数据可以存储或读取,position<=limit
  • capacity:表示缓冲区的最大容量,limit<=capacity,此值在分配缓冲区时被设置。一般不改变。

创建缓冲区:

importjava.nio.IntBuffer ;
public classIntBufferDemo{
    public static voidmain(String args[]){
        IntBuffer buf = IntBuffer.allocate(10) ;    // 准备出10个大小的缓冲区
        System.out.print("1、写入数据之前的position、limit和capacity:") ;
        System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " +buf.capacity()) ;
        int temp[] = {5,7,9} ;// 定义一个int数组
        buf.put(3) ;    // 设置一个数据
        buf.put(temp) ;    // 此时已经存放了四个记录
        System.out.print("2、写入数据之后的position、limit和capacity:") ;
        System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " +buf.capacity()) ;

        buf.flip() ;    // 重设缓冲区
        // postion = 0 ,limit = 原本position
        System.out.print("3、准备输出数据时的position、limit和capacity:") ;
        System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " +buf.capacity()) ;
        System.out.print("缓冲区中的内容:") ;
        while(buf.hasRemaining()){
            int x =buf.get() ;
            System.out.print(x + "、") ;
        }
    }
}

如果创建了缓冲区,则JVM可直接对其执行本机的IO操作

importjava.nio.ByteBuffer ;
public classByteBufferDemo{
    public static voidmain(String args[]){
        ByteBuffer buf = ByteBuffer.allocateDirect(10) ;    // 准备出10个大小的缓冲区
        byte temp[] = {1,3,5,7,9} ;    // 设置内容
        buf.put(temp) ;    // 设置一组内容
       buf.flip() ;

        System.out.print("主缓冲区中的内容:") ;
        while(buf.hasRemaining()){
            int x =buf.get() ;
            System.out.print(x + "、") ;
        }
    }
}

通道(Channel)

Java NIO的非阻塞模式,使一个线程从某通道发送请求读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取。而不是保持线程阻 塞,所以直至数据变的可以读取之前,该线程可以继续做其他的事情。 非阻塞写也是如此。一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情。 线程通常将非阻塞IO的空闲时间用于在其它通道上执行IO操作,所以一个单独的线程现在可以管理多个输入和输出通道(channel)。

Java NIO的通道类似流,但又有些不同:

  • 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
  • 通道可以异步地读写。
  • 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。

正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。

Channel的实现

这些是Java NIO中最重要的通道的实现:

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel

FileChannel 从文件中读写数据。

DatagramChannel 能通过UDP读写网络中的数据。

SocketChannel 能通过TCP读写网络中的数据。

ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。

通过通道可以完成双向的输入和输出操作。在通道还有一种方式称为内存映射

几种读入的方式的比较

RandomAccessFile   较慢

FileInputStream     较慢

缓冲读取      速度较快
内存映射      速度最快

FileChannel内存映射实例

importjava.nio.ByteBuffer ;
importjava.nio.MappedByteBuffer ;
importjava.nio.channels.FileChannel ;
importjava.io.File ;
importjava.io.FileOutputStream ;
importjava.io.FileInputStream ;
public classFileChannelDemo03{
    public static void main(String args[]) throwsException{
        File file = new File("d:" + File.separator + "oumyye.txt") ;  
        FileInputStream input = null;
        input = newFileInputStream(file) ;
        FileChannel fin = null ;    // 定义输入的通道
        fin = input.getChannel() ;    // 得到输入的通道
        MappedByteBuffer mbb = null; 
        mbb = fin.map(FileChannel.MapMode.READ_ONLY,0,file.length()) ;
        byte data[] = new byte[(int)file.length()] ;    // 开辟空间接收内容
        int foot = 0;
        while(mbb.hasRemaining()){
            data[foot++] = mbb.get() ;    // 读取数据
       }
        System.out.println(new String(data)) ;    // 输出内容
       fin.close() ;
        input.close() ;
    }
}

操作以上代码的时候,执行的是写入操作则可能是非常危险的,因为仅仅只是改变数组中的单个元素这种简单的操作,就可能直接修改磁盘上的文件,因为修改数据与数据保存在磁盘上是一样的。

 

选择器(Selectors

Selector(选择器)是Java NIO中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程可以管理多个channel,从而管理多个网络连接。

为什么使用Selector?

仅用单个线程来处理多个Channels的好处是,只需要更少的线程来处理通道。事实上,可以只用一个线程处理所有的通道。对于操作系统来说,线程之间上下文切换的开销很大,而且每个线程都要占用系统的一些资源(如内存)。因此,使用的线程越少越好。

但是,需要记住,现代的操作系统和CPU在多任务方面表现的越来越好,所以多线程的开销随着时间的推移,变得越来越小了。实际上,如果一个CPU有 多个内核,不使用多任务可能是在浪费CPU能力。不管怎么说,关于那种设计的讨论应该放在另一篇不同的文章中。在这里,只要知道使用Selector能够 处理多个通道就足够了。

要点

使用Selector可以构建一个非阻塞的网络服务。

在新IO实现网络程序需要依靠ServerSocketChannel类与SocketChannel

Selector实例

下面使用Selector完成一个简单的服务器的操作,服务器可以同时在多个端口进行监听,此服务器的主要功能是返回当前时间。

importjava.net.InetSocketAddress ;
importjava.net.ServerSocket ;
importjava.util.Set ;
importjava.util.Iterator ;
importjava.util.Date ;
importjava.nio.channels.ServerSocketChannel ;
importjava.nio.ByteBuffer ;
importjava.nio.channels.SocketChannel ;
importjava.nio.channels.Selector  ;
importjava.nio.channels.SelectionKey  ;
public classDateServer{
    public static void main(String args[]) throwsException {
        int ports[] = {8000,8001,8002,8003,8005,8006} ; // 表示五个监听端口
        Selector selector = Selector.open() ;    // 通过open()方法找到Selector
        for(int i=0;i<ports.length;i++){
            ServerSocketChannel initSer = null;
            initSer = ServerSocketChannel.open() ;    // 打开服务器的通道
            initSer.configureBlocking(false) ;    // 服务器配置为非阻塞
            ServerSocket initSock =initSer.socket() ;
            InetSocketAddress address = null;
            address = new InetSocketAddress(ports[i]) ;    // 实例化绑定地址
            initSock.bind(address) ;    // 进行服务的绑定
            initSer.register(selector,SelectionKey.OP_ACCEPT) ;    // 等待连接
            System.out.println("服务器运行,在" + ports[i] + "端口监听。") ;
        }
        // 要接收全部生成的key,并通过连接进行判断是否获取客户端的输出
        int keysAdd = 0;
        while((keysAdd=selector.select())>0){    // 选择一组键,并且相应的通道已经准备就绪
            Set<SelectionKey> selectedKeys = selector.selectedKeys() ;// 取出全部生成的key
            Iterator<SelectionKey> iter =selectedKeys.iterator() ;
            while(iter.hasNext()){
                SelectionKey key = iter.next() ;    // 取出每一个key
                if(key.isAcceptable()){
                    ServerSocketChannel server =(ServerSocketChannel)key.channel() ;
                    SocketChannel client = server.accept() ;    // 接收新连接
                    client.configureBlocking(false) ;// 配置为非阻塞
                    ByteBuffer outBuf = ByteBuffer.allocateDirect(1024) ;    //
                    outBuf.put(("当前的时间为:" + new Date()).getBytes()) ;    // 向缓冲区中设置内容
                   outBuf.flip() ;
                    client.write(outBuf) ;    // 输出内容
                    client.close() ;    // 关闭
               }
            }
            selectedKeys.clear() ;    // 清楚全部的key
       }
        
    }
}

服务器完成之后可以使用Telnet命令完成,这样就完成了一个一部的操作服务器。

131 Responses to “ JAVA中的NIO基础学习 ”

  1. best pron说道:

    Ib2sHE This is a terrific website. and i need to take a look at this just about every day of your week ,

  2. Thanks for the blog post.Really thank you! Much obliged.

  3. painting说道:

    Thanks so much for the article post.Much thanks again. Cool.

  4. your site. You have some really great articles and I feel I would be a good asset.

  5. Usually I do not read article on blogs, but I wish to say that this write-up very pressured me to take a look at and do it! Your writing style has been surprised me. Thanks, very great article.

  6. Click to read说道:

    Really informative blog article. Much obliged.

  7. Thanks so much for the blog.Much thanks again. Really Cool.

  8. This excellent website definitely has all the information and facts I needed abo

  9. Thanks for the article post.Thanks Again. Really Cool.

  10. here说道:

    What as up it as me, I am also visiting this site daily, this

  11. w88world说道:

    I will immediately clutch your rss feed as I can at to find your e-mail subscription hyperlink or e-newsletter service. Do you ave any? Please allow me recognise in order that I may subscribe. Thanks.

  12. Thanks for sharing, this is a fantastic article post.Really thank you! Awesome.

  13. Make sure that this blog will always exist.

  14. Really informative article.Really looking forward to read more. Fantastic.

  15. What as up, just wanted to say, I enjoyed this article. It was practical. Keep on posting!

  16. private Hire说道:

    Just bookmarked your blog, it is a really great and useful piece of info. I am happy that you shared this helpful tidbit with us. Please keep us up to date like this. Keep writing.

  17. Wow, fantastic weblog format! How long have you been blogging for? you make running a blog look easy. The entire glance of your web site is great, let alone the content material!

  18. status online说道:

    I really liked your blog.Really thank you! Great.

  19. check out说道:

    This is my first time pay a visit at here and i am really impressed to read all at alone place.

  20. Very nice blog post. I definitely appreciate this website. Stick with it!

  21. Green Card说道:

    Thankyou for this marvelous post, I am glad I found this website on yahoo.

  22. Must share说道:

    It as difficult to find knowledgeable people for this topic, however, you seem like you know what you are talking about! Thanks

  23. coupon tiki说道:

    I value the post.Much thanks again. Keep writing.

  24. Some really nice and useful information on this internet site, likewise I conceive the pattern has got excellent features.

  25. Nwokolo说道:

    This blog was how do I say it? Relevant!! Finally I have found something that helped me. Thanks a lot!

  26. cay thong noel说道:

    Really informative blog post.Really looking forward to read more. Fantastic.

  27. Wow, that as what I was looking for, what a stuff! present here at this website, thanks admin of this site.

  28. Thanks-a-mundo for the post.Really thank you!

  29. P. Diddy说道:

    Wow, marvelous weblog structure! How lengthy have you been blogging for? you made running a blog glance easy. The total glance of your web site is great, let alone the content material!

  30. keyword planner说道:

    It as actually very complex in this busy life to listen news on TV, thus I just use web for that reason, and take the hottest news.

  31. wanted to say that I ave truly enjoyed browsing your blog posts.

  32. In it something is also to me it seems it is excellent idea. Completely with you I will agree.

  33. Really enjoyed this post.Really looking forward to read more. Will read on

  34. You made some clear points there. I did a search on the issue and found most persons will go along with with your blog.

  35. very good, Are you contemplating taking up sport fishing.

  36. pay day loans说道:

    Seriously, such a important online site.|

  37. sua hat huu co说道:

    Spot on with this write-up, I seriously think this web site needs a lot more attention. I all probably be returning to see more, thanks for the information!

  38. I view something really special in this site.

  39. Peculiar article, totally what I needed.

  40. Online说道:

    I wanted to thank you for this excellent read!! I absolutely loved every little bit of it. I have you book-marked to look at new stuff you post

  41. visit website说道:

    This is a excellent blog, would you be interested in doing an interview about just how you designed it? If so e-mail me!

  42. tips说道:

    There is clearly a lot to know about this. I assume you made various good points in features also.

  43. womensfit说道:

    Simply wanna say that this is extremely helpful, Thanks for taking your time to write this.

  44. I value the blog post.Really looking forward to read more. Great.

  45. Hosting说道:

    What the amazing post you ave made. I merely stopped into inform you I truly enjoyed the actual read and shall be dropping by from time to time from right now on.

  46. you have done a excellent task on this topic!

  47. Tejido a crochet说道:

    Practical goal rattling great with English on the other hand find this rattling leisurely to translate.

  48. local说道:

    Im having a tiny issue. I cant get my reader to pick-up your rss feed, Im using google reader by the way.

  49. value说道:

    There as a lot of people that I think would really appreciate your content. Please let me know. Many thanks

  50. It is appropriate time to make some plans for the long run

  51. School news说道:

    Your style is so unique in comparison to other people I have read stuff from. Thanks for posting when you have the opportunity, Guess I all just bookmark this blog.

  52. School news说道:

    In it something is. Earlier I thought differently, thanks for the help in this question.

  53. This blog was how do you say it? Relevant!! Finally I ave found something that helped me. Appreciate it!

  54. Im obliged for the post.Really looking forward to read more. Want more.

  55. That is a great tip especially to those fresh to the blogosphere. Brief but very accurate info Appreciate your sharing this one. A must read article!

  56. I truly appreciate this article.Really looking forward to read more. Fantastic.

  57. this website说道:

    This blog is obviously cool additionally informative. I have chosen a bunch of useful stuff out of this blog. I ad love to return every once in a while. Thanks a lot!

  58. indeed, as bryan caplan suggests, in the past the zeal of an insurer to guard

  59. Looking forward to reading more. Great post.Really looking forward to read more. Cool.

  60. scary maze说道:

    Well I definitely liked studying it. This tip offered by you is very useful for accurate planning.

  61. Very neat article.Much thanks again. Really Great.

  62. standard information an individual provide on your guests?

  63. Wow, great blog.Really looking forward to read more. Fantastic.

  64. marketing说道:

    Somewhere in the Internet I have already read almost the same selection of information, but anyway thanks!!

  65. Real estate说道:

    I understand you sharing this post. thanks again. Much obliged.

  66. This is very interesting, You are a very skilled blogger. I ave joined your rss feed and look forward to seeking more of your excellent post. Also, I ave shared your website in my social networks!

  67. personal injury说道:

    Valuable information. Lucky me I found your web site by accident, and I am shocked why this accident didn at happened earlier! I bookmarked it.

  68. Way cool! Some very valid points! I appreciate you writing this post plus the rest of the website is extremely good.

  69. very handful of websites that occur to become comprehensive beneath, from our point of view are undoubtedly effectively really worth checking out

  70. graham dailies说道:

    I really liked your article post.Really looking forward to read more. Great.

  71. go to source说道:

    You ave made some really good points there. I looked on the web for more information about the issue and found most people will go along with your views on this web site.

  72. write for us说道:

    Whispering Misty So sorry you can expect to skip the workshop!

  73. Wow, what a video it is! Truly nice feature video, the lesson given in this video is genuinely informative.

  74. Wow, incredible blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is great, let alone the content!

  75. Thanks for sharing, this is a fantastic blog post.Really looking forward to read more.

  76. I relish, result in I found exactly what I used to be having a look for. You have ended my four day lengthy hunt! God Bless you man. Have a nice day. Bye

  77. post说道:

    Whispering Misty So sorry you can expect to miss the workshop!

  78. Thanks for a Interesting item; I enjoyed it very much. Regards Sang Magistrale

  79. You made some good points there. I looked on the internet for the issue and found most persons will go along with with your website.

  80. see more说道:

    Your style is really unique compared to other people I ave read stuff from. Many thanks for posting when you have the opportunity, Guess I will just book mark this blog.

  81. Thanks for the blog.Really looking forward to read more. Really Great.

  82. This excellent website certainly has all the information I wanted about this subject and didn at know who to ask.

  83. link说道:

    Some really great posts on this website , regards for contribution.

  84. you could have a fantastic weblog here! would you wish to make some invite posts on my weblog?

  85. launchpad pro说道:

    Spot on with this write-up, I honestly feel this amazing site needs far more attention. I all probably be back again to see more, thanks for the info!

  86. check here说道:

    Some great info on your blog, I want to read more as soon as I have sometime.

  87. go there说道:

    Incredible! This blog looks just like my old one! It as on a entirely different topic but it has pretty much the same layout and design. Superb choice of colors!

  88. disini说道:

    Your style is really unique compared to other people I have read stuff from. Thank you for posting when you ave got the opportunity, Guess I will just book mark this page.

  89. Alexander说道:

    Merely wanna input that you have a very nice site, I the style it actually stands out.

  90. lawyer miami fl说道:

    Very superb info can be found on website.

  91. you will have an ideal weblog right here! would you like to make some invite posts on my blog?

  92. genuine parts说道:

    This design is steller! You certainly know how to keep a reader amused.

  93. This post post created me feel. I will write something about this on my blog. aаАа’б‚Т€ТšаЂаŒаАТ’аЂа†

  94. Pretty! This has been an extremely wonderful article. Thanks for supplying this information.

  95. Way cool! Some extremely valid points! I appreciate you writing this write-up plus the rest of the site is also very good.

  96. Yeah bookmaking this wasn at a speculative decision great post!

  97. Keep up the good work , I read few blog posts on this web site and I conceive that your web blog is very interesting and has got sets of excellent info.

  98. This is a topic which is close to my heart Thank you! Where are your contact details though?

  99. Game Online说道:

    Really enjoyed this article post. Awesome.

  100. Thanks for the blog.Thanks Again. Great.

  101. Major thanks for the post. Really Great.

  102. I wanted to thank you for this abundant read!! I absolutely enjoyed each little crumb of it. I have got you bookmarked to ensure made known original stuff you post

  103. wow, awesome blog article.Really thank you! Keep writing.

  104. livecasinoeasy说道:

    Your style is unique in comparison to other folks I have read stuff from. Thanks for posting when you ave got the opportunity, Guess I will just book mark this site.

  105. thoroughly mixed. Promotional merchandise is a great approach to advertise your organization.

  106. Im grateful for the blog article.Much thanks again. Really Great.

  107. Wonderful post! We will be linking to this great content on our site. Keep up the good writing.

  108. the time to read or visit the subject material or web-sites we ave linked to below the

  109. Nice blog here! Also your web site loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  110. It is best to take part in a contest for among the finest blogs on the web. I all advocate this website!

  111. Muchos Gracias for your blog post. Keep writing.

  112. Im obliged for the post.Much thanks again. Fantastic.

  113. Rattling superb info can be found on blog.

  114. Well I really enjoyed reading it. This information provided by you is very constructive for accurate planning.

  115. bo dam说道:

    Say, you got a nice blog.Really looking forward to read more.

  116. Major thanks for the blog post.Really thank you! Really Cool.

  117. I truly appreciate this blog article.Really thank you! Cool.

  118. Wow! Thank you! I continually wanted to write on my website something like that. Can I take a fragment of your post to my site?

  119. In order to develop search results ranking, SEARCH ENGINE OPTIMISATION is commonly the alternative thought to be. Having said that PAID ADVERTISING is likewise an excellent alternate.

  120. Normally I don at learn post on blogs, however I wish to say that this write-up very compelled me to take a look at and do it! Your writing taste has been surprised me. Thank you, quite great post.

  121. It as best to take part in a contest for probably the greatest blogs on the web. I will advocate this site!

  122. mia pron khalifa说道:

    Jt6xqW You, my friend, ROCK! I found just the information I already searched all over the place and just could not locate it. What a perfect website.

  123. This is a beautiful picture with very good light

  124. Thanks-a-mundo for the blog article. Great.

  125. Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, as well as the content!

  126. Wow! This could be one particular of the most useful blogs We have ever arrive across on this subject. Basically Great. I am also a specialist in this topic so I can understand your hard work.

  127. I think other web-site proprietors should take this web site as an model, very clean and fantastic user friendly style and design, as well as the content. You are an expert in this topic!

  128. very nice post, i actually love this web site, carry on it

  129. know more说道:

    You will discover your selected ease and comfort nike surroundings maximum sneakers at this time there. These kinds of informal girls sneakers appear fantastic plus sense more enhanced.

  130. mens wallets说道:

    You can definitely see your skills within the work you write. The arena hopes for even more passionate writers such as you who are not afraid to say how they believe. All the time go after your heart.

  131. bistro masa说道:

    Incredible! This blog looks just like my old one! It as on a completely different subject but it has pretty much the same page layout and design. Outstanding choice of colors!

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>