1.NIO三大核心部分
缓冲区buffer:每个客户端连接对应一个buffer,读写数据通过缓冲区读写;
通道ChannelL每个channel用于连接buffer和selector,通道支持双向读写;
选择器(selector)一个选择器可以对应多个通道,用于监听多个通道的事件,selector可以监听所有的channel是否有数据需要读取,当channel有数据式就去处理,channel没有数据时,线程可以去执行其他任务
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
public class NioTest {
@Test
public void bufferTest(){
IntBuffer buffer = IntBuffer.allocate(10);
//Buffer是一个接口,这个接口有许多的实现类,例如intBuffer,longBuffer
for (int i = 0; i < 5; i++) {
buffer.put(i);
}
int i = buffer.get();//这个方法默认一个一个的从buffer取出数据
//注意buffer中维护了一个指针,由于之前的赋值操作使得指针的位置已经指向了第六的位置
//想要重头遍历需要将指针复位;
//使用flip()将指针复位
buffer.flip();
for (int j = 0; j < 5; j++) {
System.out.println(buffer.get());
}
//System.out.println(i);
//
//System.out.println(Arrays.toString(buffer.array()));
}
@Test
public void channelTest() throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("D:/a.txt");
//通向文件的贵不贵到
FileChannel channel = fileOutputStream.getChannel();
//创建一个Byte缓冲区
//ByteBuffer buffer = ByteBuffer.allocate(8);
//for (int i = 0; i < 8; i++) {
// buffer.put(Integer.toString(i).getBytes());
//}
//创建ByteBuffer的第二种方式,使用wrap一个ByteBuffer对象
ByteBuffer buffer = ByteBuffer.wrap("hello nio!".getBytes());
//使用channel的时候需要注意一个事项,输出的时候都是通过指针输出的;
//ByteBuffer buffer1 = ByteBuffer.allocate(8);
//buffer1.put("hello".getBytes());
//buffer1.flip();
//指针会往后移动,所以实际的输出是一个空的值,如果是Intbuffer则为0;所以需要将指针回调
//NIO使用buffer作为数组的读写操作,使用channel进行文件之间的连接;
channel.write(buffer);
//写出去将资源关闭
channel.close();
fileOutputStream.close();
}
}