java NIO Learning (II)

Let's look at the features and usage Channel Selector and look through the code related.

Starting first flow through us understand the most common file. A stream file corresponding to file channel is, as follows:

package stream.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
* @Description: channel测试
* @Author:      haoqiangwang3
* @CreateDate:  2020/1/10
*/
public class ChannelTest {
    public static void main(String[] args) throws IOException {
        fileChannelTest();
    }

    /**
     * 文件通道
     * @throwsIOException
      * / 
    public  static  void fileChannelTest () throws IOException {
         // set the output to the input source & file = 
        String infile = "D: \\ Work \\ Code \\ MyProject \\ spring-boot-example \\ example-test \ \ the src \\ \\ main Java NiO \\ \\ \\ rsa_private.key Stream " ; 
        String outfile =" D: \\ Work Code \\ \\ \\ MyProject Spring-Boot-Test-Example Example \\ \\ Java \\ \\ \\ main the src stream \\ \\ rsa_private_cp.key NiO " ; 

        // 1. Get the input and output data streams transmitted to the source and destination (here to the data source file = Example) 
        the FileInputStream FIN = new new the FileInputStream (INFILE); 
        a FileOutputStream FOUT = new new a FileOutputStream (outfile);

        // 2. Get input and output channels of the source data 
        FileChannel finChannel = fin.getChannel (); 
        FileChannel foutChannel = fout.getChannel (); 

        // 3. Create Object Buffer: Buffer 
        the ByteBuffer BUFF = ByteBuffer.allocate (1024 ); 

        / / 4. & channel data read from the buffer to write
         // NOTE: If the channel has been read to the end of the data, -1 is returned 
        the while (finChannel.read (BUFF) = -1! {) 

            // . 5 outgoing data preparation: buffer write mode into a read mode 
            buff.flip (); 

            // 6. the data read from the channel buffer 
            foutChannel.write (BUFF); 

            // 7. the clear buffer
             @ NOTE: be sure to remove after use 
            buff.clear (); 
        } 
    }
}

This program implements a file by file copy function channel. Codes can also be found from the contents of the file are read by a Buffer achieved. But the need to read and write modes. This method is used for the two Channel has a concept to facilitate this, let's look at the file read and write operations with a channel.

the first method:

public  static  void fileChannelTest2 () throws IOException {
         // action file address 
        String filePath = "D: \\ Work \\ Code \\ MyProject \\ spring-boot-example \\ example-test \\ src \\ main \\ java Stream \\ \\ rsa_private.key NiO \\ " ;
         // get file path, attention back operation type selection 
        FileChannel FileChannel = FileChannel.open ( new new file (filePath) .toPath (), 
                StandardOpenOption.READ, StandardOpenOption.WRITE ); 

        // Create Object buffer: buffer 
        the ByteBuffer BUFF = ByteBuffer.allocate (512 ); 

        int len = 0 ;
         // read data from the channel 
        while((len = FileChannel.read (BUFF)) = -1! ) { 

            // read the contents of buffer 
            System.out.println ( new new String (buff.array (), 0 , len)); 

            // Clear Buffer region 
            buff.clear (); 
        } 

        String STR = "written document" ; 
        buff.put (str.getBytes ()); 

        // conversion mode, the read data written to a file in the buff 
        buff.flip (); 

        // write the data to a file 
        FileChannel.write (BUFF); 

        buff.clear (); 
        fileChannel.close (); 
    }

This method is not very common, but can also achieve the effect. The second way to see the following:

/ ** 
     * This method is to write the read file, but the file is written to the front. If you want to write to a file in the back, you will need to file a pointer to the final surface, 
     * when reading a file, the file pointer will move, so read the complete contents of a file and then write, additional effects can be achieved 
     * / 
    public  static  void fileChannelTest3 () { 
        a RandomAccessFile the aFile = null ;
         the try { 
            the aFile = new new a RandomAccessFile ( "D: \\ \\ Work Code MyProject \\ \\ \\ Example Spring-Boot-Test-Example the src \\ \\ \\ main Stream NiO \\ \\ \\ Java rsa_private.key "," RW " ); 

            // get the file path 
            FileChannel FileChannel = aFile.getChannel (); 

            // create a buffer 
            the ByteBuffer BUFF = ByteBuffer.allocate (1024 );

            STR String = "a RandomAccessFile written document" ;
             // write data to the buff 
            buff.put (str.getBytes ()); 

            // conversion mode, the data is written to a file buff 
            buff.flip (); 

            // the data is written to a file buff 
            FileChannel.write (buff);
             // Clear buffer 
            buff.clear (); 

            int len = 0 ;
             the while ! ((len = FileChannel.read (buff)) = -1 ) 
            { 
                // read the contents of buffer 
                System.out.println ( new new String (buff.array (), 0 , len)); 

                // Clear buffer 
                 buff.clear ();
            }

            fileChannel.close();
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(aFile != null){
                    aFile.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

It can be found by the above code, FileChannel by RandomAccessFile, FileInputStream, to obtain FileOutputStream.

 


Channel introduced here, and below Selector will introduce SocketChannel together, the most common is that we've written before an upgraded version socket connection is achieved with the NIO server socket communication.

code show as below:

 

package stream.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SelectorTest {
    public static void main(String[] args) throws IOException, InterruptedException {

        //Creating serverSocketChannel, listening 8081 port 
        ServerSocketChannel ServerSocketChannel = ServerSocketChannel.open (); 
        . ServerSocketChannel.socket () the bind ( new new InetSocketAddress ( "127.0.0.1", 8081 ));
         // set to non-blocking mode 
        serverSocketChannel.configureBlocking ( false ); 

        // to serverSocketChannel registered Selector 
        Selector Selector = Selector.open (); 
        serverSocketChannel.register (Selector, SelectionKey.OP_ACCEPT); 

        System.out.println ( "NIO socket Server start ..." ); 

        the while ( to true ) {
             // be blocked by this
            the selector.select (); 

            System.out.println ( "begin processing requests ..." ); 
            the Set <the SelectionKey> Keys = selector.selectedKeys (); 
            the Iterator <the SelectionKey> IT = keys.iterator ();
             the while (IT. the hasNext ()) {
                 // Get need of treatment the SelectionKey 
                the SelectionKey Key = it.next (); 

                // treated 
                Handler (Key); 

                // process the acquired event needs to be removed 
                it.remove (); 
            } 
        } 
    } 

    / * * 
     * operates differently depending on the state of the key 
     * @param key
     *@throws IOException 
     * @throws InterruptedException
      * / 
    public  static  void Handler (the SelectionKey Key) throws IOException, InterruptedException { 

        IF (key.isAcceptable ()) { 
            System.out.println ( "... request acceptable state" );
             // get SocketChannel 
            SocketChannel SocketChannel = . ((ServerSocketChannel) key.channel ()) the Accept (); 

            // set to non-blocking 
            socketChannel.configureBlocking ( false ); 

            // Selector registration concerned, readable event
            socketChannel.register (key.selector (), SelectionKey.OP_READ); 

            System.out.println ( "established connection request ..." ); 
        } 
        IF (key.isReadable ()) { 

            System.out.println ( "this request is a read state ... " ); 
            the Thread.sleep ( 10000 ); 
            the SocketChannel SocketChannel = (the SocketChannel) key.channel (); 

            // create a buffer 
            the ByteBuffer ByteBuffer.allocate = buffer (512 ); 

            // read customer content sent by 
            int len = 0 ;
             the while ! ((len = socketChannel.read (Buffer)) = -1  ) {
                System.out.println ( "received content:" + new new String (buffer.array (), 0 , len));
                 // Clear Buffer 
                buffer.clear (); 
            } 

            // return information about the client 
            String respStr = "Hello World" ; 
            buffer.put (respStr.getBytes ()); 

            // conversion mode 
            buffer.flip (); 
            socketChannel.write (Buffer); 

            buffer.clear (); 
            // establish a connection needs to close 
            socketChannel.close (); 
        } 
    } 
}

 

Run the server, you can socket in the forehead by a client to communicate before. We can find him through to blocking selector.select () method, by continuously registered in rotation in the above passage he found the correspondence processing operations after the operation he was interested.

Guess you like

Origin www.cnblogs.com/wanghq1994/p/12176973.html