Java Nio feature learning (1)

Source: Internet
Author: User

Java Nio feature learning (1)
Java NIO feature learning

Java NIO contains several core components:

ChannelsBufferSelectorsChannels

It can be understood as a stream of resources. The stream resource can read Data from the Channel to a Buffer or write Data from a Buffer to the Channel;

Channel Implementations

Integrate common channels in JDK 7

FileChannel: reads or writes data to an operating file. mongoramchannel: reads or writes data from a network UDP connection. SocketChannel: reads or writes data from a TCP network connection. ServerSocketChannel: you can use this Channel to listen to TCP connections, just as when the Web Server is connected, you can create a SocketChannelBase Channel Example

Read Data from Channel

 

 

  1. RandomAccessFile aFile =newRandomAccessFile(data/nio-data.txt,rw);
  2. FileChannel inChannel = aFile.getChannel();
  3.  
  4. ByteBuffer buf =ByteBuffer.allocate(48);
  5.  
  6. //write data to buffer
  7. int bytesRead = inChannel.read(buf);
  8. while(bytesRead!=-1){
  9.  
  10. System.out.println(Read + bytesRead);
  11. //swither buffer type to read data from buffer
  12. buf.flip();
  13.  
  14. while(buf.hasRemaining()){
  15. System.out.print((char) buf.get());
  16. }
  17.  
  18. buf.clear();
  19. bytesRead= inChannel.read(buf);
  20. }
  21. aFile.close();

     

    Buffer

    Java NIO Buffers and Channels are used in combination,Read from channels into buffer, writtern from buffers into channels

    Buffer Usage calls buffer to write data to buffer. the flip () method uses buffer. the get () method calls buffer to obtain data. clear () or buffer. compact () clears read data
    
      
    1. RandomAccessFile aFile = new RandomAccessFile(data/nio-data.txt , rw);
    2. FileChannel inChannel = aFile.getChannel();
    3. //Create Buffer with capacity of 48 byte
    4. ByteBuffer buf = ByteBuffer.allocate(48);
    5.  
    6. int bytesRead = inChannel.read(buf);
    7.  
    8. while(bytesRead!=-1){
    9.  
    10. buf.flip(); //make buffer ready for read
    11.  
    12. while(buf.hasRemaining()){
    13. System.out.print((char) buf.get()); // read 1 byte at a time
    14. }
    15.  
    16. buf.clear(); //make buffer ready for writing
    17. bytesRead = inChannel.read(buf);
    18. }
    Buffer Capacity, Position and Limit

    Capacity

    When a Buffer is created, a memory block of the specified size is allocated, and only the fixed size of data can be written to the buffer when writing data. If the Buffer is full, read or clear is required to continue writing.

    Position

    Position: The reading mode and mode have different meanings. After Bufer init, the Position value is 0. when data is written to one byte, the Position of long etc Buffer is moved to the next Position. AndPosition<=Capacity-1

    Whenfilp()When reading data from the Bufferset position = 0, Position will move down with the reading process;

    Limit

    In Write mode, Limit is equal to the value of Capacity, indicating how much data can be written to the Buffer.

    Callfilp()In Reade Modeset limit = positionIndicates the maximum amount of data that can be read.

    Commonly used Buffer implementation bytebuffermappedbytebuffercharbufferdoublebufferfloatbufferintbufferlongbuffer=buffersomemethods of BufferAllocating a Buffer

    Useallocate()To allocate the Buffer size.

    ByteBuffer buf = ByteBuffer. allocate (48 );
    CharBuffer buf = CharBuffer. allocate (1024 );

    Write Data to a Buffer

    There are two ways to write data to the Buffer:

     

    Read data from the Channel and write data into the Buffer. Call the Buffer.put()Method to write data

     

    Int bytesRead = inChannel. read (buf); // read into buffer.
    Buf. put (127 );
    Flip ()

    Convert the write status to the read status. Action:set limit = position ; set position=0 ;

    Reading Data from a Buffer

    Two methods:

     

    Read data from the Buffer to the Channel to read the data in the Buffer. You can use the built-in buffer method.get()Etc

     

    // Read from buffer into channel.
    Int bytesWritten = inChannel. write (buf );
    Byte aByte = buf. get ();
    Rewind ()

    set position=0

    Mark () and reset ()

    Mark is used until the position of the hitting record. Then, you can use the reset method to reset the position to the position of the mark record.

    Scatter/Gather/Transfers

    The Channel can read data into multiple buffers.
    The Channel can write data from multiple buffers to the Channle.
    Channels can be converted between Channle, includingtransferFrom() & transferTo

    Scatter Reads:

    For example, I read the html header part to the first buffer and read the body part to the second Buffer.

    
      
    1. ByteBuffer header = ByteBuffer.allocate(128);
    2. ByteBuffer body = ByteBuffer.allocate(1024);
    3.  
    4. ByteBuffer[] bufferArray = { header, body };
    5.  
    6. channel.read(buffers);
    Gather Writes

    
      
    1. ByteBuffer header = ByteBuffer.allocate(128);
    2. ByteBuffer body = ByteBuffer.allocate(1024);
    3.  
    4. //write data into buffers
    5.  
    6. ByteBuffer[] bufferArray = { header, body };
    7.  
    8. channel.write(buffers);
    TransfersTransferFrom ()
    
      
    1. RandomAccessFile fromFile = new RandomAccessFile(fromFile.txt, rw);
    2. FileChannel fromChannel = fromFile.getChannel();
    3.  
    4. RandomAccessFile toFile = new RandomAccessFile(toFile.txt, rw);
    5. FileChannel toChannel = toFile.getChannel();
    6.  
    7. long position = 0;
    8. long count = fromChannel.size();
    9.  
    10. toChannel.transferFrom(fromChannel, position, count);
    TransferTo ()
    
      
    1. RandomAccessFile fromFile = new RandomAccessFile(fromFile.txt, rw);
    2. FileChannel fromChannel = fromFile.getChannel();
    3.  
    4. RandomAccessFile toFile = new RandomAccessFile(toFile.txt, rw);
    5. FileChannel toChannel = toFile.getChannel();
    6.  
    7. long position = 0;
    8. long count = fromChannel.size();
    9.  
    10. fromChannel.transferTo(position, count, toChannel);
    Selector

    The Selector component can run to determine multiple channels and dynamically decide which Channel to use to perform Read or Write operations. You can use this component to launch a Thread to manage multiple Channels or multiple network connection Channels.

    Create a Selector

    UseSelector.open()Method To create a Selector

    Selector selector = Selector. open ();

    Register Channels to Selector

    To allow Selector to manage Channels, you need to callSelector.register()Register with Selector

    Channel. configureBlocking (false); // The Channel must be in non-blocking mode to be used with a Selector
    SelectionKey key = channel. register (selector, SelectionKey. OP_READ );
    When registering a Channel, you must specify the events that the Channel needs to care about. The events include:

    Connect-> SelectionKey. OP_CONNECTAccept-> SelectionKey. OP_ACCEPTRead-> SelectionKey. OP_READWrite-> SelectionKey. OP_WRITE
    If you register multiple events, you can useint interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;Passint interestSet = selectionKey.interestOps();All Selector's events can be obtained.

    Simple Demo:

    
      
      1. Selector selector = Selector.open();
      2.  
      3. channel.configureBlocking(false);
      4.  
      5. SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
      6.  
      7.  
      8. while(true) {
      9.  
      10. int readyChannels = selector.select();
      11.  
      12. if(readyChannels == 0) continue;
      13.  
      14.  
      15. Set selectedKeys = selector.selectedKeys();
      16.  
      17. Iterator keyIterator = selectedKeys.iterator();
      18.  
      19. while(keyIterator.hasNext()) {
      20.  
      21. SelectionKey key = keyIterator.next();
      22.  
      23. if(key.isAcceptable()) {
      24. // a connection was accepted by a ServerSocketChannel.
      25.  
      26. } else if (key.isConnectable()) {
      27. // a connection was established with a remote server.
      28.  
      29. } else if (key.isReadable()) {
      30. // a channel is ready for reading
      31.  
      32. } else if (key.isWritable()) {
      33. // a channel is ready for writing
      34. }
      35.  
      36. keyIterator.remove();
      37. }
      38. }

     

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.