NIO
2.1 NIO Overview
NIO
NIO ==> New IO (New IO), Non-Block IO (non-blocking IO)
NIO non-blocking IO, running current affairs program in dealing with IO, will not affect the operation of other programs, you can not use multiple threads in case, IO meet operational requirements.
Three core components:
Channel
Channel
file operations, network operations using the data transfer channel
buffer
Buffer
buffer may be provided using operating efficiency, reduce the number of unnecessary reader
selector
Selector
True core
2.2 Buffer Channel complete file operations
2.3.1 Common API
java.nio.Buffer
Buffer Buffer
ByteBuffer byte buffer used
ShortBuffer
IntBuffer
LongBuffer
CharBuffer byte buffer used
FloatBuffer
the DoubleBuffer
Common methods:
public static the ByteBuffer the allocate (int Capacity);
according to the number of bytes allocated buffer space corresponding to the designated bytes of data stored
public byte get ();
reads a byte from a byte array buffer object
public final buffer flip ();
flip buffer back to the beginning of the buffer.
public static ByteBuffer wrap (byte [] arr);
into a byte array to a buffer, a new one will be the ByteBuffer
public static PUT the ByteBuffer (byte [] B);
an array of bytes into the buffer to
Channel interfaces, channel interface
FileChannel file operation channel
DatagramChannel UDP packet protocol operation Channel
a ServerSocketChannel corresponding to the TCP server ServerSocket Channel
the SocketChannel Channel corresponding to the TCP Socket client
first file operation to Example FileChannel
public long read (ByteBuffer buffer);
from the channel ByteBuffer read data to the
public long write (ByteBuffer buffer);
write data into the channel from the Buffer
public long transferFrom (ReadableByteChannel src, long position, long count)
from the specified srcChannel, starting at the position specified position, the read element count , the channel to the current
file copy operation.
public long transferTo (long position, long count, WritableByteChannel target)
to write the data in the current channel to the target, starting from the position of the current position of the channel, the count count
File operation code is as follows:
import org.junit.Test;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileNioTest {
/*
通过NIO写入数据到文件中的操作
*/
@Test
public void testNioFileWrite() throws IOException {
// 1. 文件操作字节输出流
FileOutputStream fos = new FileOutputStream("D:/aaa/1.txt");
// 2. 利用文件操作输出字节流对象获取对应的Channel通道
FileChannel foc = fos.getChannel();
// 3. 准备一个缓冲区 4KB缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024 * 4);
// 4. 准备数据,放入缓冲区
String str = "测试NIO";
buffer.put(str.getBytes());
// 5. 存在缓冲区数据放入之后,缓冲区指针发生改变,到达存入数据的末尾
// 如果此时调用写入操作,会从存入缓冲区之后开始保存
// 让缓冲区指针回到最初的起点,并且操作写入程序,只会保存缓冲区内的有效数据
buffer.flip();
// 6. 缓冲区数据写入到通道中
foc.write(buffer);
// 7. 关闭资源
fos.close();
}
@Test
public void testNioFileRead() throws IOException {
// 1. 文件字节操作输入流
FileInputStream fis = new FileInputStream("D:/aaa/1.txt");
// 2. FileChannel
FileChannel fic = fis.getChannel();
// 3. 准备缓冲
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 4. 从Channel读取数据保存到缓冲区中
int read = fic.read(buffer);
System.out.println(read);
// 5. 展示数据
// String(byte[] arr, int off, int count)
System.out.println(new String(buffer.array(), 0, read));
// 6. 关闭资源
fis.close();
}
// 130
@Test
public void testCopyFile() throws IOException {
long start = System.currentTimeMillis();
// 1. 安排输出流和输入流
FileInputStream fis = new FileInputStream("D:/aaa/1.mp4");
FileOutputStream fos = new FileOutputStream("D:/aaa/2.mp4");
// 2. 准备两个Channel
FileChannel srcChannel = fis.getChannel();
FileChannel dstChannel = fos.getChannel();
// 3. 拷贝方法
srcChannel.transferTo(0, srcChannel.size(), dstChannel);
// dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
// 4. 关闭资源
fos.close();
fis.close();
long end = System.currentTimeMillis();
System.out.println("Time:" + (end - start));
}
// 300
@Test
public void testCopyUseBuffer() throws IOException {
long start = System.currentTimeMillis();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/aaa/1.mp4"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/aaa/3.mp4"));
int length = -1;
byte[] buf = new byte[4 * 1024];
while ((length = bis.read(buf)) != -1) {
bos.write(buf, 0, length);
}
bos.close();
bis.close();
long end = System.currentTimeMillis();
System.out.println("Time:" + (end - start));
}
}
Note Notes
2.3 network programming using NIO [focus]
2.3.1 Selector Selector Boss
Selector
Selector, network programming using the NIO brother! ! !
The server can execute a thread running Selector program, listening to operate.
New connection, is connected, reading data, writing data
Selector common methods:
public static Selector the Open ();
to give a selected object
public int select (long timeout);
listen to all channels registered, operations are IO streams exist, the corresponding information will be deposited into the collection SelectionKey inside, the parameter is a timeout
public set <SelectionKey> selectionKeys () ;
return the current stored in the internal collection Selector all SelectionKey
2.3.2 SelectionKey
SelectionKey
represent network channels and Selector direct relationship
int OP_ACCEPT; 16 needs to be connected
int OP_CONNECT; 8 connected
int OP_READ; 1 reading operation
int OP_WRITE; 4 writes
SelectionKey
public abstract Selector Selector ();
to give the object is associated Selector
public abstract SelectableChannel channel ();
obtained channel associated
public final Object attachment ();
to obtain data associated with the shared
public abstract SelectionKey interestOps (int ops) ;
set or changed event listener
public final boolean isAcceptable ();
can the Accept
public boolean Final isReadable ();
if you can read
public final boolean isWritable ();
if you can write
2.3.3 ServerSocketChannel
ServerSocketChannel
Channel Socket server program channel corresponding to
common methods:
public static ServerSocketChannel Open ();
turn on the server ServerSocketChannel channel, equal to the starting server program
public final ServerSocketChannel bind (SocketAddress local) ;
set port number server
public final SelectableChannel configureBlocking (boolean block) ;
set blocking or non-blocking mode, the value represents the non-blocking mode false
public the SocketChannel Accept ();
[nonblocking]
Gets a client connection, and the operation to obtain the corresponding channel
public final SelectionKey register (Selector sel, int ops);
[emphasis method]
Register selector, and choose what event monitor
2.3.4 SocketChannel
SocketChannel
client Channel object corresponding to the Socket
Common methods:
public static the SocketChannel Open ();
punch a Channel object Socket client
public final SelectableChannel configureBlocking (boolean block)
there may be provided a blocked state or a non-blocking state
to false, indicating nonblocking
public boolean connect (SocketAddress remote);
connector server
public boolean finishConnect ();
if connect the connection fails, the connection can continue through the finishConnect
public int write (the ByteBuffer buf);
write data into the buffer stream
public int read (ByteBuffer buf); ,
reads data from the buffer stream
public final SelectionKey register (Selector sel, int ops , Object attechment);
Register the SocketChannel, select a corresponding listening operation, and may have parameters Object attachment
public final void close ();
Close SocketChannel