欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java NIO学习(一)

程序员文章站 2022-03-02 15:28:18
...

1.Java NIO的概述

Java NIO由3个核心部分组成:Channels,Buffers,Selectors。

Channel的类型有:FileChannel,DatagramChannel,SocketChannel,ServerSocketChannel

Buffer的类型有:ByteBuffer,CharBuffer,DoubleBuffer,FloatBuffer,IntBuffer,ShortBuffer,LongBuffer,MappedByteBuffer

Selector允许单线程处理多个Channel。如果打开了多个连接通道,但每个连接的流量都很低。使用Selector就会很方便。

2.Channel

FileChannel:从文件种读写数据

DatagramChannel:能通过UDP读写网络种的数据

SocketChannel:能读写TCP读写网络种的数据

ServerSocketChannel:可以监听新进来的TCP连接。

基本Channel读取文件实例

    @Test
    public void readTest(){
        RandomAccessFile accessFile= null;
        try {
            accessFile = new RandomAccessFile("D:/nio-data.txt","rw");
            FileChannel fileChannel=accessFile.getChannel();
            //创建缓冲区
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            //从通道读取数据到缓冲区
            int count =fileChannel.read(buffer);
            while (count!=-1){
                //反转缓冲区(limit设置为position,position设置为0,mark设置为-1)
                buffer.flip();
                //判断是否有元素
                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get());
                }
                //读完将缓冲区还原
                buffer.clear();
                //判断是否还有数据
                count=fileChannel.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(accessFile!=null) {
                    accessFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

 基本Channel写入文件实例

  @Test
    public void wirteTest(){
        RandomAccessFile accessFile= null;
        try {
            accessFile = new RandomAccessFile("D:/IDEA_workspace/springCloud2/product/src/test/java/com/product/NIO1/data/nio-data.txt","rw");
            Person person=new Person("1",23,"test");
            Person person1=new Person("1",23,"test");
            accessFile.write(person.toString().getBytes());
            accessFile.write("\n".toString().getBytes());
            accessFile.write(person1.toString().getBytes());
            //让定位到文件最后
            accessFile.seek(accessFile.length());
            //追加
            accessFile.write("\n我".toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                accessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

相关标签: nio