NIO 解释

NIO 是一种 IO 模型,相对于经典 IO,是非阻塞的。

NIO 模型


相比经典 io 基于流的传输,NIO 采用的是缓冲区的方式,基于块的传输

Channel 分类

  • FileChannel
    • FileChannnel 允许你向文件里读写内容
  • DatagramChannel
    • DatagramChannel 允许你通过 UDP 协议读写网络上的内容
  • SocketChannel
    • SocketChannel 允许你通过 TCP 协议读写网络上的内容
  • ServerSocketChannel
    • allows you to listen for incoming TCP connections, like a web server does. For each incoming connection a SocketChannel is created.

NIO 读写文件 Demo

public static void main(String[] args) throws IOException {
        RandomAccessFile afile=new RandomAccessFile("E:\\Nio.txt","rw");//使用RandomAccessFile创建文件对象
        FileChannel fileChannel=afile.getChannel();//获取channel
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);//创建buffer
        String mess="fighting for beatiful girl";
        int j=fileChannel.read(byteBuffer);//这个j代表了一次读出来的字符个数
        while (j!=-1){
            System.out.println("reads: "+j);
//            byteBuffer.flip();//这个flip很重要,修改buffer的模式,由写模式转换为读模式
//            while (byteBuffer.hasRemaining()){//把字符读完
//                System.out.print((char)byteBuffer.get());
//            }
//            byteBuffer.clear();//本次独处的字符输出完了,清空bytebuffer。
            j=fileChannel.read(byteBuffer);//buffer此时又是写模式
        }
        byte[] we=mess.getBytes(StandardCharsets.UTF_8);

        byteBuffer.put(we);
        byteBuffer.flip();//将buffer切换为读模式
        fileChannel.write(byteBuffer);//将buffer里的东西写入文件
        afile.close();//关闭文件资源
    }

Buffer

buffer 的使用步骤

Using a Buffer to read and write data typically follows this little 4-step process:

  1. Write data into the Buffer
  2. Call buffer.flip()
  3. Read data out of the Buffer
  4. Call buffer.clear() or buffer.compact()

buffer 的三个参数

  • capacity
  • position
  • limit

Capacity

Being a memory block, a Buffer has a certain fixed size, also called its “capacity”. You can only write capacity bytes, longs, chars etc. into the Buffer. Once the Buffer is full, you need to empty it (read the data, or clear it) before you can write more data into it.

Position

  • When you write data into the Buffer, you do so at a certain position. Initially the position is 0. When a byte, long etc. has been written into the Buffer the position is advanced to point to the next cell in the buffer to insert data into. Position can maximally become capacity - 1.

  • When you read data from a Buffer you also do so from a given position. When you flip a Buffer from writing mode to reading mode, the position is reset back to 0. As you read data from the Buffer you do so from position, and position is advanced to next position to read.

Limit

In write mode the limit of a Buffer is the limit of how much data you can write into the buffer. In write mode the limit is equal to the capacity of the Buffer.

When flipping the Buffer into read mode, **limit means the limit of how much data you can read from the data. **Therefore, when flipping a Buffer into read mode, limit is set to write position of the write mode. In other words, you can read as many bytes as were written (limit is set to the number of bytes written, which is marked by position).

buffer 的类别

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer

每个基本类型,都有相应的 Buffer

初始化 buffer

ByteBuffer buf = ByteBuffer.allocate(48);//用的最多的Buffer

CharBuffer buf = CharBuffer.allocate(1024);

向 buffer 中写入数据

int bytesRead = inChannel.read(buf); //read into buffer.从channel中读取数据,写入到buffer

buf.put(127);    //直接往buffer里put数据

flip()

The flip() method switches a Buffer from writing mode to reading mode. Calling flip() sets the position back to 0, and sets the limit to where position just was.
In other words, position now marks the reading position, and limit marks how many bytes, chars etc. were written into the buffer - the limit of how many bytes, chars etc. that can be read.

将 buffer 从写模式切换到读模式。limit 为 buffer 中有多少数据,position 切换为 0;

从 buffer 中读取数据

There are two ways you can read data from a Buffer.

  1. Read data from the buffer into a channel.
  2. Read data from the buffer yourself, using one of the get() methods.

int bytesWritten = inChannel.write(buf);//从buffer中读取数据,并写入channel,返回一个int,代表写入了多少数据
byte aByte = buf.get();//获取一个字符

There are many other versions of the get() method, allowing you to read data from the Buffer in many different ways. For instance, reading at specific positions, or reading an array of bytes from the buffer. See the JavaDoc for the concrete buffer implementation for more details.

rewind()

The Buffer.rewind() sets the position back to 0, so you can reread all the data in the buffer. The limit remains untouched, thus still marking how many elements (bytes, chars etc.) that can be read from the Buffer.

将 buffer 的 position 设置为 0;这样就可以从 0 开始读取数据。limit 不改变

clear() and compact()

Once you are done reading data out of the Buffer you have to make the Buffer ready for writing again. You can do so either by calling clear() or by calling compact().
If you call clear() the position is set back to 0 and the limit to capacity. In other words, the Buffer is cleared. The data in the Buffer is not cleared. Only the markers telling where you can write data into the Buffer are.
If there is any unread data in the Buffer when you call clear() that data will be “forgotten”, meaning you no longer have any markers telling what data has been read, and what has not been read.
If there is still unread data in the Buffer, and you want to read it later, but you need to do some writing first, call compact() instead of clear().
compact() copies all unread data to the beginning of the Buffer. Then it sets position to right after the last unread element. The limit property is still set to capacity, just like clear() does. Now the Buffer is ready for writing, but you will not overwrite the unread data.

当你读了数据之后,应该调用 clear 方法或者 compact 方法来使 buffer 重新可读。

  1. clear 方法会将 position 设置为 0;limit 设置为 capacity 大小。但是数据并不会清空。同时你也不会知道是否还有数据没有读,有未读的数据你也读不出来。
  2. compact 方法,会将未读的数据移到 buffer 的开头,并将 position 置为未读的数据的最后一位,limit 依然设置为 capacity,但是你不会覆写未读的数据。

mark() and reset()

You can mark a given position in a Buffer by calling the Buffer.mark() method. You can then later reset the position back to the marked position by calling the Buffer.reset() method. Here is an example:

buffer.mark();
//call buffer.get() a couple of times, e.g. during parsing.
buffer.reset();  //set position back to mark.

你可以调用 mark 方法。将 buffer 此时的 position 标记起来。并可通过 reset 方法,恢复到标记的位点