IO 与 NIO 的比较
IO | NIO |
---|---|
面向流(Stream Oriented) | 面向缓冲区(Buffer Oriented) |
阻塞IO(Blocking IO) | 非阻塞IO(Non Blocking IO) |
无 | 选择器(Selectors) |
通道和缓冲区
- 通道(Channel):负责传输(铁路)
- 缓冲区(Buffer):负责存储(火车)
缓冲区(buffer)
一、根据数据类型的不同,提供了相应类型的缓冲区(Boolean 除外)
ByteBuffer
CharBuffer
IntBuffer
LongBuffer
ShortBuffer
FloatBuffer
DoubleBuffer
上述缓冲区的管理方式几乎一致,通过 allocate() 获取缓冲区
二、缓冲区存取数据的两个核心方法
- put() : 存入数据到缓冲区
- get() : 获取缓冲区中的数据
三、缓冲区的四个核心属性
- capacity:容量,缓冲区中最大存储数据的容量,一旦声明不能改变
- limit:界限,缓冲区中可以操作的数据的大小,(limit之后的数据不能进行读写)
- position:位置,缓冲区中正在操作的数据的位置
- mark:记录当前 position 的位置,可以通过 reset(),恢复到 mark 的位置
- 0 <= mark <= position <= limit <= capacity
- position 和 limit 就像两个指针(或者游标)在 0 到 capacity 之间移动
四、直接缓冲区,非直接缓冲区
- 非直接缓冲区:通过 allocate() 方法分配缓冲区,将缓冲区建立在 JVM 的内存中
- 直接缓冲区:通过 alocateDir() 方法分配直接缓冲区,将缓冲区建立在物理内存,可以提高效率
- 判断是否为直接缓冲区:buffer.isDirect();
五、代码实践
void contextLoads() {
// 分配指定大小的缓冲区
System.out.println("============== allocate ================");
ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 0
System.out.println(buffer.limit()); // 1024
// 添加数据
System.out.println("============== put ================");
String str = "brave";
buffer.put(str.getBytes());
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 5
System.out.println(buffer.limit()); // 1024
// 切换到读数据模式
System.out.println("============== flip ================");
buffer.flip();
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 0
System.out.println(buffer.limit()); // 5
// 读取数据
System.out.println("============== get ================");
byte[] bst = new byte[buffer.limit()];
buffer.get(bst);
System.out.println(new String(bst)); // brave
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 5
System.out.println(buffer.limit()); // 5
// 可重复读
System.out.println("============== rewind ================");
buffer.rewind();
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 0
System.out.println(buffer.limit()); // 5
// 清空缓冲区(数据依然存在)
System.out.println("============== clear ================");
buffer.clear();
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 0
System.out.println(buffer.limit()); // 1024
System.out.println((char)buffer.get()); // b
}
void bufTest(){
System.out.println("========= mark =========");
ByteBuffer buffer = ByteBuffer.allocate(1024);
String str = "brave";
buffer.put(str.getBytes());
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 5
System.out.println(buffer.limit()); // 1024
buffer.flip();
byte[] bst = new byte[buffer.limit()];
buffer.get(bst,0,2);
System.out.println(new String(bst,0,2)); // br
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 2
System.out.println(buffer.limit()); // 5
// 标记 position = 2
buffer.mark();
buffer.get(bst,2,2);
System.out.println(new String(bst,2,2)); // av
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 4
System.out.println(buffer.limit()); // 5
// 返回到标记点 position = 2
buffer.reset();
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 2
System.out.println(buffer.limit()); // 5
// 缓冲区中是否还有数据
if(buffer.hasRemaining()){
// 返回缓冲区中剩余的数据个数
System.out.println(buffer.remaining()); // 3
}
}
通道(channel)
一、通道的主要实现类
- java.nio.channels.Channel 接口:
|-- FileChannel(本地文件)
|-- SocketChannel(TCP)
|-- ServerSocketChannel(TCP)
|-- DategramChannel(UDP)
二、获取通道
- 1、java 针对支持通道的类提供了 getChannel() 方法
- 本地IO:
FileInputStream / FileOutputStream
RandomAccessFile - 网络IO:
Socket
ServerSocket
DatagramSocket
- 本地IO:
- 2、在 JDK1.7 中的 NIO.2 针对各个通道提供了静态方法 open()
- 3、在 JDK1.7 中的 NIO.2 的 Files 工具类的 newByteChannel()
三、通道之间的数据传输
- transferFrom()
- transferTo()
四、分散(Scatter)与聚集(Gather)
- 分散读取(Scattering Reads):将通道中的数据分散到多个缓冲区中
- 聚集写入(Gathering Writes):将多个缓冲区中的数据聚集到通道中
五、字符集:CharSet
- 编码:字符串 -> 字符数组
- 解码:字符数组 -> 字符串
使用 NIO 完成本地通信
- 利用通道完成文件复制
@Test
void channelTest() throws Exception{
FileInputStream fis = new FileInputStream("1.jpg");
FileOutputStream fos = new FileOutputStream("2.jpg");
// 获取通道
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel();
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 将通道中的数据存入缓冲区
while(inChannel.read(buf) != -1){
// 切换到读数据模式
buf.flip();
// 将缓冲区中的数据写入通道
outChannel.write(buf);
// 清空通道
buf.clear();
}
outChannel.close();
inChannel.close();
fos.close();
fis.close();
}
- 使用直接缓冲区完成文件的复制(内存映射文件)
@Test
void channelTest() throws Exception{
FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
// 内存映射文件
MappedByteBuffer inMappedByteBuffer = inChannel.map(MapMode.READ_ONLY,0, inChannel.size());
MappedByteBuffer outMappedByteBuffer = outChannel.map(MapMode.READ_WRITE,0, inChannel.size());
// 直接对缓冲区进行数据的读写操作
byte[] dst = new byte[inMappedByteBuffer.limit()];
inMappedByteBuffer.get(dst);
outMappedByteBuffer.put(dst);
outChannel.close();
inChannel.close();
}
- 通道之间的数据传输(直接缓冲区)
@Test
void channelTest() throws Exception{
FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("5.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
// inChannel.transferTo(0, inChannel.size(),outChannel);
outChannel.transferFrom(inChannel, 0, inChannel.size());
outChannel.close();
inChannel.close();
}
- 分散读取,聚集写入
@Test
void channelTest() throws Exception{
RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");
// 获取通道
FileChannel channel = raf1.getChannel();
// 分配指定大小的缓冲区
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(1024);
// 分散读取
ByteBuffer[] bufs = {buf1, buf2};
channel.read(bufs);
for(ByteBuffer byteBuffer : bufs){
byteBuffer.flip();
}
System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
System.out.println("---------------------");
System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));
// 聚集写入
RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw");
FileChannel channel2 = raf2.getChannel();
channel2.write(bufs);
raf1.close();
raf2.close();
}
- 字符编码
// 查看所有支持的编码
void charset() throws Exception{
Map<String,Charset> map = Charset.availableCharsets();
Set<Entry<String,Charset>> set = map.entrySet();
for(Entry<String,Charset> entry:set){
System.out.println(entry.getKey()+"="+entry.getValue());
}
}
// 编码器,解码器
void charsetTest() throws Exception{
Charset cs1 = Charset.forName("GBK");
// 获取编码器
CharsetEncoder ce = cs1.newEncoder();
// 获取解码器
CharsetDecoder cd = cs1.newDecoder();
CharBuffer cBuf = CharBuffer.allocate(1024);
String str = "心有猛虎细嗅蔷薇";
cBuf.put(str);
cBuf.flip();
// 编码
ByteBuffer bBuf = ce.encode(cBuf);
for(int i= 0;i < str.length() * 2;i++){
System.out.println(bBuf.get());
}
// 解码
bBuf.flip();
CharBuffer cBuf2 = cd.decode(bBuf);
System.out.println(cBuf2.toString());
}
使用 NIO 完成网络通信
一、通道(Channel) :负责连接
- java . nio. channels .Channel 接口
- SelectableChannel
- SocketChannel
- ServerSocketChannel
- Datagr amChannel
- Pipe. SinkChannel
- Pipe. SourceChannel
- SelectableChannel
二、缓冲区(Buffer) :负责数据的存取
三、迭择器(Selector) :
- 是 SelectableChannel 的多路复用器。用于监控 SelectableChannel 的 IO 状况
四、代码实践
- 阻塞式 IO
public class Aserver {
public static void main(String[] args) throws Exception{
// 获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
FileChannel outChannel = FileChannel.open(Paths.get("3.txt"),StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);
// 绑定连接
ssChannel.bind(new InetSocketAddress(9898));
// 获取客户端链接的通道
SocketChannel sChannel = ssChannel.accept();
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 接收客户端的数据,保存到本地
while(sChannel.read(buf) != -1){
buf.flip();
outChannel.write(buf);
buf.clear();
}
// 发送反馈给客户端
buf.put("服务端接收数据成功".getBytes());
buf.flip();
sChannel.write(buf);
// 关闭通道
sChannel.close();
outChannel.close();
ssChannel.close();
}
}
public class Aclient {
public static void main(String[] args) throws Exception{
// 获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
FileChannel inChannel = FileChannel.open(Paths.get("1.txt"), StandardOpenOption.READ);
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 读取本地文件,发送到服务器
while(inChannel.read(buf) != -1){
buf.flip();
sChannel.write(buf);
buf.clear();
}
sChannel.shutdownOutput();
// 接收服务端反馈
int len = 0;
while((len = sChannel.read(buf)) != -1){
buf.flip();
System.out.println(new String(buf.array(),0,len));
buf.clear();
}
// 关闭通道
inChannel.close();
sChannel.close();
}
}
- 非阻塞式 IO
public class Aserver {
public static void main(String[] args) throws Exception{
// 获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
// 切换成非阻塞模式
ssChannel.configureBlocking(false);
// 绑定连接
ssChannel.bind(new InetSocketAddress(9898));
// 获取选择器
Selector selector = Selector.open();
// 将通道注册到选择器,指定监听事件
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
// 轮询式的获取选择器上已经准备就绪的事件
while(selector.select() >0 ){
// 获取当前选择器中所有注册的"选择键(已就绪的监听事件)"
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
// 获取准备就绪的事件
SelectionKey sk = it.next();
// 判断具体是什么事件准备就绪
if(sk.isAcceptable()){
// 若“接收就绪”,获取客户端连接
SocketChannel sChannel = ssChannel.accept();
// 切换成非阻塞模式
sChannel.configureBlocking(false);
// 将通道注册到选择器上
sChannel.register(selector, SelectionKey.OP_READ);
}else if (sk.isReadable()){
// 获取当前选择器上“读就绪”状态的通道
SocketChannel sChannel = (SocketChannel) sk.channel();
// 读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
int len = 0;
while((len = sChannel.read(buf)) >0 ){
buf.flip();
System.out.println(new String(buf.array(),0,len));
buf.clear();
}
}
// 取消 SelectionKey
it.remove();
}
}
// 关闭通道
// ssChannel.close();
}
}
public class Aclient {
public static void main(String[] args) throws Exception{
// 获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
// 切换成非阻塞模式
sChannel.configureBlocking(false);
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 发送数据给服务端
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String str = scanner.next();
buf.put((new Date().toString() + " " + str).getBytes());
buf.flip();
sChannel.write(buf);
buf.clear();
}
// 关闭通道
sChannel.close();
}
}
- 基于 UDP 实现的非阻塞式 IO
public class Areceive {
public static void main(String[] args) throws IOException {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
dc.bind(new InetSocketAddress(9898));
Selector selector = Selector.open();
dc.register(selector, SelectionKey.OP_READ);
while(selector.select() > 0){
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()){
SelectionKey sk = it.next();
if(sk.isReadable()){
ByteBuffer buf = ByteBuffer.allocate(1024);
dc.receive(buf);
buf.flip();
System.out.println(new String(buf.array(),0,buf.limit()));
buf.clear();
}
}
it.remove();
}
}
}
public class Asend {
public static void main(String[] args) throws IOException {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
ByteBuffer buf = ByteBuffer.allocate(1024);
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.next();
buf.put((new Date().toString() + " "+ str).getBytes());
buf.flip();
dc.send(buf,new InetSocketAddress("127.0.0.1",9898));
buf.clear();
}
dc.close();
}
}
管道
- Java NIO 管道是2个线程之间的单向数据连接。
- Pipe 有一个 source 通道和一个 sink 通道。
- 数据会被写到 sink 通道,从 source 通道 读取。
public class Test {
public static void main(String[] args) throws IOException {
// 获取管道
Pipe pipe = Pipe.open();
// 将缓冲区中的数据写入管道
ByteBuffer buf = ByteBuffer.allocate(1024);
Pipe.SinkChannel sinkChannel = pipe.sink();
buf.put("通过单向管道发送数据".getBytes());
buf.flip();
sinkChannel.write(buf);
// 读取缓冲区中的数据
Pipe.SourceChannel sourceChannel = pipe.source();
buf.flip();
int len = sourceChannel.read(buf);
System.out.println(new String(buf.array(),0,len));
sinkChannel.close();
sourceChannel.close();
}
}