美文网首页
7.Nio代码学习

7.Nio代码学习

作者: 八颗小牙坏脾气 | 来源:发表于2018-12-20 16:25 被阅读0次

    1

    public class NioTest01 {
        public static void main(String[] args) {
            IntBuffer buffer = IntBuffer.allocate(10);
    
            for (int i = 0, j = buffer.capacity(); i < j; i++) {
                int random = new SecureRandom().nextInt(20);
                buffer.put(random);
            }
    
            buffer.flip();
    
            while (buffer.hasRemaining()) {
                System.out.println(buffer.get());
            }
        }
    }
    

    2

    public class NioTest02 {
        public static void main(String[] args) throws Exception {
            FileInputStream fileInputStream = new FileInputStream("NioTest02.txt");
            FileChannel channel = fileInputStream.getChannel();
    
            ByteBuffer buffer = ByteBuffer.allocate(512);
            channel.read(buffer);
    
            buffer.flip();
    
            while (buffer.hasRemaining()) {
                byte b = buffer.get();
                System.out.printf("%c", b);
            }
    
            // 一定不要忘记
            fileInputStream.close();
        }
    }
    

    3

    public class NioTest03 {
        public static void main(String[] args) throws Exception {
            FileOutputStream fileOutputStream = new FileOutputStream("nioTest03.txt");
            FileChannel fileChannel = fileOutputStream.getChannel();
    
            ByteBuffer byteBuffer = ByteBuffer.allocate(512);
    
            byte[] message = "hello world, welcome sumi~".getBytes();
    
            for (int i = 0; i < message.length; i++) {
                byteBuffer.put(message[i]);
            }
    
            byteBuffer.flip();
    
            fileChannel.write(byteBuffer);
            fileOutputStream.close();
    
        }
    }
    

    4

    public class NioTest04 {
        public static void main(String[] args) throws Exception {
            FileInputStream inputStream = new FileInputStream("input.txt");
            FileOutputStream outputStream = new FileOutputStream("output.txt");
            FileChannel inputChannel = inputStream.getChannel();
            FileChannel outputChannel = outputStream.getChannel();
    
            ByteBuffer buffer = ByteBuffer.allocate(4);
    
            while (true) {
                //very very important 此代码注释掉,会造成死循环的写入
                buffer.clear();
    
                int read = inputChannel.read(buffer);
                System.out.println(read);
                if (read == -1) {
                    break;
                }
    
                //important
                buffer.flip();
    
                outputChannel.write(buffer);
            }
    
            inputStream.close();
            outputStream.close();
        }
    }
    

    5

    public class NioTest05 {
        public static void main(String[] args) {
            ByteBuffer buffer = ByteBuffer.allocate(64);
    
            buffer.putInt(20);
            buffer.putChar('韩');
            buffer.putLong(380380380L);
            buffer.putDouble(20.4d);
            buffer.put((byte) 13);
            buffer.putFloat(11.1f);
            buffer.putShort((short) 10);
    
            buffer.flip();
            System.out.println(buffer.getInt());
            System.out.println(buffer.getChar());
            System.out.println(buffer.getLong());
            System.out.println(buffer.getDouble());
            System.out.println(buffer.get());
            System.out.println(buffer.getFloat());
            System.out.println(buffer.getShort());
        }
    }
    

    6

    /**
     * @author sm121
     * @date 2018/12/20.
     * slice 与原有的 buffer共享相同的底层数组
     * shift + esc 关闭Terminal窗口
     * tab键,用于更新后面的代码 buffer.position(2);  buffer.limit tab
     */
    public class NioTest06 {
        public static void main(String[] args) {
            ByteBuffer buffer = ByteBuffer.allocate(10);
    
            for (int i = 0; i < buffer.capacity(); i++) {
                buffer.put((byte) i);
            }
    
            // [2,5)
            buffer.position(2);
            buffer.limit(5);
    
            ByteBuffer slice = buffer.slice();
    
            for (int i = 0; i < slice.capacity(); i++) {
                byte b = slice.get(i);
                b *= 2;
                slice.put(i, b);
            }
    
            buffer.position(0);
            buffer.limit(buffer.capacity());
    
            while (buffer.hasRemaining()) {
                System.out.println(buffer.get());
            }
        }
    }
    

    7

    /**
     * @author sm121
     * @date 2018/12/20.
     * 普通buffer 可以转为 只读buffer,反过来不行。为什么
     */
    public class NioTest07 {
        public static void main(String[] args) {
            ByteBuffer buffer = ByteBuffer.allocate(10);
    
            System.out.println(buffer.getClass());
    
            for (int i = 0; i < buffer.capacity(); i++) {
                buffer.put((byte) i);
            }
    
            ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
    
            System.out.println(readOnlyBuffer.getClass());
    
            readOnlyBuffer.flip();
    
            while (readOnlyBuffer.hasRemaining()) {
                System.out.println(readOnlyBuffer.get());
            }
        }
    }
    
    

    8

    public class NioTest08 {
        public static void main(String[] args) throws Exception {
            ByteBuffer buffer = ByteBuffer.allocateDirect(10);
        }
    }
    

    9

    /**
     * @author sm121
     * @date 2018/12/21.
     * 内存映射文件,位于堆外内存
     */
    public class NioTest09 {
        public static void main(String[] args) throws Exception {
            RandomAccessFile file = new RandomAccessFile("neicunyingshe.txt", "rw");
    
            FileChannel channel = file.getChannel();
    
            MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, 10);
            map.putChar(0, 'c');
            map.putChar(2, 'z');
    
        }
    }
    

    10

    public class NioTest10 {
        public static void main(String[] args) throws Exception {
            RandomAccessFile file = new RandomAccessFile("test.txt", "rw");
            FileChannel channel = file.getChannel();
            FileLock lock = channel.lock(0, 10, true);
    
            System.out.println("shared:" + lock.isShared());
            System.out.println("valid:" + lock.isValid());
        }
    }
    

    11

    public class NioTest11 {
        public static void main(String[] args) throws Exception {
            int[] ports = new int[]{6666, 6667, 6668, 6669};
    
            Selector selector = Selector.open();
    
            for (int i = 0; i < ports.length; i++) {
                ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                serverSocketChannel.configureBlocking(false);
    
                ServerSocket serverSocket = serverSocketChannel.socket();
                InetSocketAddress inetAddress = new InetSocketAddress(ports[i]);
                // bind
                serverSocket.bind(inetAddress);
    
                //register
                serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                System.out.println("监听端口:" + ports[i]);
            }
    
            while (true) {
                int numbers = selector.select();
                System.out.println("numbers: " + numbers);
    
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                System.out.println("selected keys: " + selectionKeys);
    
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
    
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
    
                    if (selectionKey.isAcceptable()) {
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
    
                        socketChannel.register(selector, SelectionKey.OP_READ);
    
                        //一定要注意移除
                        iterator.remove();
                        System.out.println("获得客户端连接:" + socketChannel);
                    } else if (selectionKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
    
                        int bytesRead = 0;
    
                        while (true) {
                            ByteBuffer buffer = ByteBuffer.allocate(512);
                            buffer.clear();
    
                            int read = socketChannel.read(buffer);
                            if (read <= 0) {
                                break;
                            }
                            buffer.flip();
                            socketChannel.write(buffer);
    
                            bytesRead += read;
                        }
                        System.out.println("读取:" + bytesRead + ",来自于" + socketChannel);
    
                        //一定要注意移除
                        iterator.remove();
                    }
    
                }
    
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:7.Nio代码学习

          本文链接:https://www.haomeiwen.com/subject/apoykqtx.html