【Netty】学习笔记-01【NIO基础】
持续上传更新中~
前言
- Netty官网:https://netty.io/
- 官方学习文档:https://netty.io/4.1/api/index.html
- 视频学习地址:https://www.bilibili.com/video/BV1py4y1E7oA
NIO 基础
NIO(
non-blocking io
) :非阻塞 IO
说明:有的资料将 NIO 翻译为 new io,是因为NIO是在JDK1.4后加入
java.nio全称java non-blocking IO,是指jdk1.4 及以上版本里提供的新api(New IO) ,为所有的原始类型(boolean类型除外)提供缓存支持的数据容器,使用它可以提供非阻塞式的高伸缩性网络。
Sun 官方标榜的特性如下: 为所有的原始类型提供(Buffer)缓存支持。字符集编码解码解决方案。 Channel :一个新的原始I/O 抽象。 支持锁和内存映射文件的文件访问接口。 提供多路(non-blocking) 非阻塞式的高伸缩性网络I/O 。
java.nio 详细简介可参照百度百科:https://baike.baidu.com/item/java.nio
1. 三大组件
1.1 Channel
channel 有一点类似于 stream,它就是读写数据的双向通道,可以从 channel 将数据读入 buffer,也可以将 buffer 的数据写入 channel,而之前的 stream 要么是输入,要么是输出,channel 比 stream 更为底层。
常见的 Channel 有:
- FileChannel(文件通道)
- DatagramChannel(数据报通道;UDP)
- SocketChannel(承插槽;TCP;客户端&服务器)
- ServerSocketChannel(服务器承插槽;TCP;服务器专用)
1.2 Buffer
buffer 则用来缓冲读写数据
常见的 buffer 有:
- ByteBuffer(字节缓冲;最常用;抽象类,下面3个是实现类)
- MappedByteBuffer
- DirectByteBuffer
- HeapByteBuffer
- ShortBuffer
- IntBuffer
- LongBuffer
- FloatBuffer
- DoubleBuffer
- CharBuffer
1.3 Selector
selector(选择器) 单从字面意思不好理解,需要结合服务器设计的演化来理解它的用途。
a>多线程版设计
多线程版缺点:
- 内存占用高
- 线程上下文切换成本高(线程同时执行的最大个数取决于CPU)
- 只适合连接数少的场景
b>线程池版设计
线程池版缺点:
- 阻塞模式下,线程仅能处理一个 socket 连接
- 仅适合短连接场景(早期Tomcat采用的就是阻塞式IO进行短连接)
c>selector版设计
selector 的作用就是配合一个线程来管理多个 channel,获取这些 channel 上发生的事件,这些 channel 工作在非阻塞模式下,不会让线程吊死在一个 channel 上。适合连接数特别多,但流量低的场景(low traffic)。
调用 selector 的 select()
会阻塞,直到 channel 发生了读写就绪事件,这些事件发生,select 方法就会返回这些事件交给 thread 来处理。
2. ByteBuffer 基本使用
首先通过一个读取文件案例来了解ByteBuffer的基本使用,然后详细介绍其中的api的含义及用法。
有一普通文本文件 data.txt,内容为:
1234567890abc
使用 FileChannel 来读取文件内容:
package com.min.netty.c1;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @Date: 2022/7/6
* @Version: 1.0
* @Author: YiMin
* @Description: ByteBuffer-基本使用(查看/输出/打印 data.txt文件)
*/
@Slf4j
public class TestByteBuffer {
/**
* FileChannel 可以通过两种方式生成:
* 1.输入输出流 2. RandomAccessFile
*/
public static void main(String[] args) {
/**
* 1.通过传统方式 RandomAccessFile 生成FileChannel
*/
try (RandomAccessFile file = new RandomAccessFile("data.txt", "rw")) {
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(10);
do {
// 向 buffer 写入
int len = channel.read(buffer);
log.debug("读到字节数:{}", len);
if (len == -1) {
break;
}
// 切换 buffer 读模式
buffer.flip();
while(buffer.hasRemaining()) {
log.debug("{}", (char)buffer.get());
}
// 切换 buffer 写模式
buffer.clear();
} while (true);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 2.通过文件输入流的方式 FileInputStream 获得FileChannel
*/
@Test
public void test01(){
/**
* 2.1 定义了buffer的空间大小,写入文件数据,但是打印出数据只有分配空间大小的数据,未完全打印
*/
try (FileChannel channel = new FileInputStream("data.txt").getChannel()){
// 1.准备缓冲区
ByteBuffer buffer = ByteBuffer.allocate(10);
// 2.从 channel 读取数据,即向 buffer 写入
channel.read(buffer);
// 3.打印 buffer 的内容
buffer.flip(); //切换至读模式
while (buffer.hasRemaining()) { //检测是否还有剩余的未读数据
byte b = buffer.get();
System.out.println((char)b); //强转成字符打印
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test02(){
/**
* 2.2 通过增加while循环,打印出完全内容,注意在每次循环打印的最后切换为写模式
*/
try (FileChannel channel = new FileInputStream("data.txt").getChannel()){
// 1.准备缓冲区
ByteBuffer buffer = ByteBuffer.allocate(10);
while (true) {
// 2.从 channel 读取数据,即向 buffer 写入
int len = channel.read(buffer);
if (len == -1) {
break;
}
// 3.打印 buffer 的内容
buffer.flip(); //切换至读模式
while (buffer.hasRemaining()) { //检测是否还有剩余的未读数据
byte b = buffer.get();
System.out.println((char)b); //强转成字符打印
}
buffer.clear(); //切换为写模式
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test03(){
/**
* 2.3 通过引入 logback.xml文件,并使用 @Slf4j 注解类,将日志输出代替简单的控制台打印
*/
try (FileChannel channel = new FileInputStream("data.txt").getChannel()){
// 1.准备缓冲区
ByteBuffer buffer = ByteBuffer.allocate(10);
while (true) {
// 2.从 channel 读取数据,即向 buffer 写入
int len = channel.read(buffer);
log.debug("读取到的字节数:{}",len);//使用日志输出
if (len == -1) {
break;
}
// 3.打印 buffer 的内容
buffer.flip(); //切换至读模式
while (buffer.hasRemaining()) { // 是否还有剩余未读数据
byte b = buffer.get();
log.debug("实际字节:{}",(char)b);//使用日志输出
}
buffer.clear(); // 切换为写模式
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
main方法输出:
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 读到字节数:10
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 1
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 2
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 3
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 4
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 5
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 6
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 7
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 8
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 9
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 0
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 读到字节数:3
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - a
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - b
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - c
00:38:21 [DEBUG] [main] c.m.n.c.TestByteBuffer - 读到字节数:-1
test01()方法输出:
1
2
3
4
5
6
7
8
9
0
test02()方法输出:
1
2
3
4
5
6
7
8
9
0
a
b
c
test03()方法输出:
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 读取到的字节数:10
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:1
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:2
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:3
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:4
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:5
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:6
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:7
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:8
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:9
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:0
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 读取到的字节数:3
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:a
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:b
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 实际字节:c
00:40:59 [DEBUG] [main] c.m.n.c.TestByteBuffer - 读取到的字节数:-1
a>logback.xml
注意:logger 命名空间引入的包路径
<?xml version="1.0" encoding="UTF-8"?>
<configuration
xmlns="http://ch.qos.logback/xml/ns/logback"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ch.qos.logback/xml/ns/logback logback.xsd">
<!-- 输出控制,格式控制-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date{HH:mm:ss} [%-5level] [%thread] %logger{17} - %m%n </pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 日志文件名称 -->
<file>logFile.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天产生一个新的日志文件 -->
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 保留 15 天的日志 -->
<maxHistory>15</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date{HH:mm:ss} [%-5level] [%thread] %logger{17} - %m%n </pattern>
</encoder>
</appender>
<!-- 用来控制查看那个类的日志内容(对mybatis name 代表命名空间) -->
<logger name="com.min" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
<logger name="io.netty.handler.logging.LoggingHandler" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
<root level="ERROR">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
2.1 ByteBuffer 使用步骤
- 向 buffer 写入数据,例如调用
channel.read(buffer)
- 调用
flip()
切换至读模式 - 从 buffer 读取数据,例如调用
buffer.get()
- 调用
clear()
或compact()
切换至写模式 - 重复 1~4 步骤
2.2 ByteBuffer 内部结构
ByteBuffer 有以下重要属性:
- capacity(容量)
- position(读写指针;索引位置)
- limit(读写限制)
一开始:
写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态:
flip 动作发生后,position 切换为读取位置,limit 切换为读取限制:
读取 4 个字节后,状态:
clear 动作发生后,状态:
compact 方法,是把未读完的部分向前压缩,然后切换至写模式:
a>调试工具类
调试工具类,是为了直观地打印出 ByteBuffer 中的内容,帮助我们更加清楚的观看api方法调用时,其中ByteBuffer的内部结构是如何变化的,包括容量、索引位置及读写切换。
注意:引入的包名名称!!且要在pom.xml中引入netty依赖!!
package com.min.netty.c1;
import io.netty.util.internal.StringUtil;
import java.nio.ByteBuffer;
import static io.netty.util.internal.MathUtil.isOutOfBounds;
import static io.netty.util.internal.StringUtil.NEWLINE;
/**
* ByteBuffer 调试工具类
*/
public class ByteBufferUtil {
private static final char[] BYTE2CHAR = new char[256];
private static final char[] HEXDUMP_TABLE = new char[256 * 4];
private static final String[] HEXPADDING = new String[16];
private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
private static final String[] BYTE2HEX = new String[256];
private static final String[] BYTEPADDING = new String[16];
static {
final char[] DIGITS = "0123456789abcdef".toCharArray();
for (int i = 0; i < 256; i++) {
HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
}
int i;
// Generate the lookup table for hex dump paddings
for (i = 0; i < HEXPADDING.length; i++) {
int padding = HEXPADDING.length - i;
StringBuilder buf = new StringBuilder(padding * 3);
for (int j = 0; j < padding; j++) {
buf.append(" ");
}
HEXPADDING[i] = buf.toString();
}
// Generate the lookup table for the start-offset header in each row (up to 64KiB).
for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
StringBuilder buf = new StringBuilder(12);
buf.append(NEWLINE);
buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
buf.setCharAt(buf.length() - 9, '|');
buf.append('|');
HEXDUMP_ROWPREFIXES[i] = buf.toString();
}
// Generate the lookup table for byte-to-hex-dump conversion
for (i = 0; i < BYTE2HEX.length; i++) {
BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
}
// Generate the lookup table for byte dump paddings
for (i = 0; i < BYTEPADDING.length; i++) {
int padding = BYTEPADDING.length - i;
StringBuilder buf = new StringBuilder(padding);
for (int j = 0; j < padding; j++) {
buf.append(' ');
}
BYTEPADDING[i] = buf.toString();
}
// Generate the lookup table for byte-to-char conversion
for (i = 0; i < BYTE2CHAR.length; i++) {
if (i <= 0x1f || i >= 0x7f) {
BYTE2CHAR[i] = '.';
} else {
BYTE2CHAR[i] = (char) i;
}
}
}
/**
* 打印所有内容
* @param buffer
*/
public static void debugAll(ByteBuffer buffer) {
int oldlimit = buffer.limit();
buffer.limit(buffer.capacity());
StringBuilder origin = new StringBuilder(256);
appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
System.out.println("+--------+-------------------- all ------------------------+----------------+");
System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
System.out.println(origin);
buffer.limit(oldlimit);
}
/**
* 打印可读取内容
* @param buffer
*/
public static void debugRead(ByteBuffer buffer) {
StringBuilder builder = new StringBuilder(256);
appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
System.out.println("+--------+-------------------- read -----------------------+----------------+");
System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
System.out.println(builder);
}
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put(new byte[]{97, 98, 99, 100});
debugAll(buffer);
}
private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
if (isOutOfBounds(offset, length, buf.capacity())) {
throw new IndexOutOfBoundsException(
"expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
+ ") <= " + "buf.capacity(" + buf.capacity() + ')');
}
if (length == 0) {
return;
}
dump.append(
" +-------------------------------------------------+" +
NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" +
NEWLINE + "+--------+-------------------------------------------------+----------------+");
final int startIndex = offset;
final int fullRows = length >>> 4;
final int remainder = length & 0xF;
// Dump the rows which have 16 bytes.
for (int row = 0; row < fullRows; row++) {
int rowStartIndex = (row << 4) + startIndex;
// Per-row prefix.
appendHexDumpRowPrefix(dump, row, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + 16;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(" |");
// ASCII dump
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append('|');
}
// Dump the last row which has less than 16 bytes.
if (remainder != 0) {
int rowStartIndex = (fullRows << 4) + startIndex;
appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + remainder;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(HEXPADDING[remainder]);
dump.append(" |");
// Ascii dump
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append(BYTEPADDING[remainder]);
dump.append('|');
}
dump.append(NEWLINE +
"+--------+-------------------------------------------------+----------------+");
}
private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
if (row < HEXDUMP_ROWPREFIXES.length) {
dump.append(HEXDUMP_ROWPREFIXES[row]);
} else {
dump.append(NEWLINE);
dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
dump.setCharAt(dump.length() - 9, '|');
dump.append('|');
}
}
public static short getUnsignedByte(ByteBuffer buffer, int index) {
return (short) (buffer.get(index) & 0xFF);
}
}
2.3 ByteBuffer 常见方法
代码演示
package com.min.netty.c1;
import java.nio.ByteBuffer;
import static com.min.netty.c1.ByteBufferUtil.debugAll;
/**
* @Date: 2022/7/6
* @Version: 1.0
* @Author: YiMin
* @Description: ByteBuffer 常见方法-演示
*/
public class TestByteBufferReadWrite {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
/**
* 演示写模式 put(字节/字节数组)
*/
buffer.put((byte) 0x61); // 'a'
debugAll(buffer); //调用ByteBuffer调试工具类中debugAll()方法,直观打印ByteBuffer内容
System.out.println();
buffer.put(new byte[]{0x62,0x63,0x64}); // 'b','c','d'
debugAll(buffer);
System.out.println();
/**
* 演示读模式 get(索引)
*/
System.out.println("未切换为读模式,此时字节为:" + buffer.get());//0,当前索引位置在4
System.out.println();
buffer.flip(); //切换为读模式
System.out.println("已切换为读模式,此时字节为:" + buffer.get());//97,当前索引位置在0,,当前64(十六进制)转为97(十进制)输出
System.out.println();
debugAll(buffer);//此时执行debugAll,索引位置向后移动一位,当前索引位置为1
System.out.println();
/**
* 演示 compact()方法:将未读的字节前移至已读位置 注意此时已转为写模式
*/
buffer.compact();
debugAll(buffer);
System.out.println();
/**
* 执行了compact()方法后即切换为了写模式,此时写入数据,注意观察刚刚前移位置最后一位字节由保留转为此时写入的第一个索引位置
*/
buffer.put(new byte[]{0x65,0x66});
debugAll(buffer);
}
}
输出:
+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 00 00 00 00 00 00 00 00 00 |a......... |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [4], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 00 00 00 00 00 00 |abcd...... |
+--------+-------------------------------------------------+----------------+
未切换为读模式,此时字节为:0
已切换为读模式,此时字节为:97
+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [5]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 00 00 00 00 00 00 |abcd...... |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [4], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 63 64 00 00 00 00 00 00 00 |bcd....... |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [6], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 63 64 00 65 66 00 00 00 00 |bcd.ef.... |
+--------+-------------------------------------------------+----------------+
a>分配空间
可以使用allocate(指定容量大小)
为 ByteBuffer 分配空间,其它 buffer 类也有该方法。
ByteBuffer buf= ByteBuffer.allocate(16);
注意:通过allocate方法指定的buffer空间大小是固定的,不能动态调整;后面学习的netty会对此做增强,可以动态调整buffer空间大小。
allocate 与 allocateDirect 区别:
public class TestByteBufferAllocate {
public static void main(String[] args) {
// ByteBuffer.allocate(16)
System.out.println(ByteBuffer.allocate(16).getClass());
//ByteBuffer.allocateDirect(16)
System.out.println(ByteBuffer.allocateDirect(16).getClass());
/**
* class java.nio.HeapByteBuffer - java 堆内存
* 1)读写效率低; 2)受到GC的影响
*
* class java.nio.DirectByteBuffer - 直接内存
* 1)读写效率高(少一次拷贝); 2)不会受到GC影响; 3)分配的效率低; 4)若资源释放不完全易造成内存泄漏
*
* 引申:netty对allocateDirect方法做了很好的封装,对分配效率做了提升
*/
}
}
b>向 buffer 写入数据
向 buffer 写入数据有两种办法:
1)调用channel的read
方法
int readBytes = channel.read(buf);
2)调用buffer自己的put
方法
buf.put((byte)127);
c>从 buffer 读取数据
从 buffer 读取数据同样有两种办法:
1) 调用channel的write
方法
int writeBytes = channel.write(buf);
2)调用buffer自己的get
方法
byte b = buf.get();
get 方法会让 position 读指针向后走,如果想重复读取数据
- 可以调用
rewind
方法将 position 重新置为 0- 或者调用
get(int i)
方法获取索引 i 的内容,它不会移动读指针
1)演示 rewind 方法:
public class TestByteBufferRead {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10); //指定分配空间大小
buffer.put(new byte[]{'a','b','c','d'}); //写模式,插入字节数组
buffer.flip(); //切换为读模式
/**
* rewind 从头开始读
*/
buffer.get(new byte[4]);
debugAll(buffer);//abcd
//通过get方法读取4个字节后,指针会在4位置上,此时想重新再读取,需要通过rewind方法
buffer.rewind();
System.out.println("重新读取第一个字节,字节为:" + (char)buffer.get());// a
}
}
输出:
1)演示 get(int i) 方法:
public class TestByteBufferRead {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10); //指定分配空间大小
buffer.put(new byte[]{'a','b','c','d'}); //写模式,插入字节数组
buffer.flip(); //切换为读模式
/**
* get(i) 不会改变读索引的位置
*/
System.out.println((char) buffer.get(3));//d
debugAll(buffer);
}
}
输出:
d>mark 和 reset
mark 是在读取时,做一个标记,即使 position 改变,只要调用 reset 就能回到 mark 的位置。
注意
rewind 和 flip 都会清除 mark 位置
演示 mark 和 reset 方法:
public class TestByteBufferRead {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10); //指定分配空间大小
buffer.put(new byte[]{'a','b','c','d'}); //写模式,插入字节数组
buffer.flip(); //切换为读模式
/**
* mark & reset
* mark:做一个标记,记录position位置;reset:将position重置到mark的位置,方便再次读取
*/
System.out.println((char) buffer.get());//a
System.out.println((char) buffer.get());//b
buffer.mark(); //加标记,索引为2的位置
System.out.println((char) buffer.get());//c
System.out.println((char) buffer.get());//d
buffer.reset(); //将position重置到索引2
System.out.println((char) buffer.get());//c
System.out.println((char) buffer.get());//d
}
}
e>字符串与 ByteBuffer 互转
字符串转为 ByteBuffer
- ByteBuffer.put(“字符串”.getBytes());
- Charset.forName(“utf-8”).encode(“字符串”);
- StandardCharsets.UTF_8.encode(“字符串”);
- ByteBuffer.wrap(“字符串”.getBytes());
ByteBuffer 转为字符串
- String str = StandardCharsets.UTF_8.decode(buffer).toString();
public class TestByteBufferString {
public static void main(String[] args) {
/**
* 字符串转为 ByteBuffer
*/
// 1. getBytes()
//注意转换后ByteBuffer还是写模式,若读取需切换读模式,否则读取为空
ByteBuffer buffer1 = ByteBuffer.allocate(16);
buffer1.put("hello1".getBytes());
debugAll(buffer1);
// 2. Charset
ByteBuffer buffer2 = Charset.forName("utf-8").encode("hello2");
debugAll(buffer2);
// 3. 标准Charset:StandardCharsets
ByteBuffer buffer3 = StandardCharsets.UTF_8.encode("hello3");
debugAll(buffer3);
// 4. wrap
//(NIO提供的工具类,在字节数组和ByteBuffer之间做了一个包装)
ByteBuffer buffer4 = ByteBuffer.wrap("hello4".getBytes());
debugAll(buffer4);
/**
* ByteBuffer 转为字符串
*/
buffer1.flip();//切换读模式!!!
String str1 = StandardCharsets.UTF_8.decode(buffer1).toString();
System.out.println(str1);
String str2 = StandardCharsets.UTF_8.decode(buffer2).toString();
System.out.println(str2);
String str3 = StandardCharsets.UTF_8.decode(buffer3).toString();
System.out.println(str3);
CharBuffer bytebuffer3 = StandardCharsets.UTF_8.decode(buffer4);
System.out.println(bytebuffer3.getClass());
System.out.println(bytebuffer3.toString());
}
}
输出:
+--------+-------------------- all ------------------------+----------------+
position: [6], limit: [16]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f 31 00 00 00 00 00 00 00 00 00 00 |hello1..........|
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [6]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f 32 |hello2 |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [6]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f 33 |hello3 |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [6]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f 34 |hello4 |
+--------+-------------------------------------------------+----------------+
hello1
hello2
hello3
class java.nio.HeapCharBuffer
hello4
f>Buffer 的线程安全
Buffer 是非线程安全的
3. 文件编程
3.1 FileChannel
a>FileChannel 工作模式
FileChannel 只能工作在阻塞模式下
b>获取
不能直接打开 FileChannel,必须通过 FileInputStream、FileOutputStream 或者 RandomAccessFile 来获取 FileChannel,它们都有 getChannel 方法
- 通过 FileInputStream 获取的 channel 只能读
- 通过 FileOutputStream 获取的 channel 只能写
- 通过 RandomAccessFile 是否能读写根据构造 RandomAccessFile 时的读写模式决定
c>读取
会从 channel 读取数据填充 ByteBuffer,返回值表示读到了多少字节,-1
表示到达了文件的末尾
int readBytes = channel.read(buffer);
d>写入
写入的正确姿势如下, SocketChannel
ByteBuffer buffer = ...;
buffer.put(...); // 存入数据
buffer.flip(); // 切换读模式
while(buffer.hasRemaining()) {
channel.write(buffer);
}
在 while 中调用 channel.write 是因为 write 方法并不能保证一次将 buffer 中的内容全部写入 channel
e>关闭
channel 必须关闭,不过调用了 FileInputStream、FileOutputStream 或者 RandomAccessFile 的 close 方法会间接地调用 channel 的 close 方法
f>位置
获取当前位置:
long pos = channel.position();
设置当前位置:
long newPos = ...;
channel.position(newPos);
设置当前位置时,如果设置为文件的末尾:
- 这时读取会返回 -1
- 这时写入,会追加内容,但要注意如果 position 超过了文件末尾,再写入时在新内容和原末尾之间会有空洞(00)
g>大小
使用 size 方法获取文件的大小
h>强制写入
操作系统出于性能的考虑,会将数据缓存,不是立刻写入磁盘。可以调用 force(true) 方法将文件内容和元数据(文件的权限等信息)立刻写入磁盘
3.2 两个 Channel 传输数据
String FROM = "helloword/data.txt";
String TO = "helloword/to.txt";
long start = System.nanoTime();
try (FileChannel from = new FileInputStream(FROM).getChannel();
FileChannel to = new FileOutputStream(TO).getChannel();
) {
from.transferTo(0, from.size(), to);
} catch (IOException e) {
e.printStackTrace();
}
long end = System.nanoTime();
System.out.println("transferTo 用时:" + (end - start) / 1000_000.0);
输出:
transferTo 用时:8.2011
超过 2g 大小的文件传输:
public class TestFileChannelTransferTo {
public static void main(String[] args) {
try (
FileChannel from = new FileInputStream("data.txt").getChannel();
FileChannel to = new FileOutputStream("to.txt").getChannel();
) {
// 效率高,底层会利用操作系统的零拷贝进行优化
long size = from.size();
// left 变量代表还剩余多少字节
for (long left = size; left > 0; ) {
System.out.println("position:" + (size - left) + " left:" + left);
left -= from.transferTo((size - left), left, to);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
实际传输一个超大文件:
position:0 left:7769948160
position:2147483647 left:5622464513
position:4294967294 left:3474980866
position:6442450941 left:1327497219
3.3 Path
jdk7 引入了 Path 和 Paths 类
- Path 用来表示文件路径
- Paths 是工具类,用来获取 Path 实例
Path source = Paths.get("1.txt"); // 相对路径 使用 user.dir 环境变量来定位 1.txt
Path source = Paths.get("d:\\1.txt"); // 绝对路径 代表了 d:\1.txt
Path source = Paths.get("d:/1.txt"); // 绝对路径 同样代表了 d:\1.txt
Path projects = Paths.get("d:\\data", "projects"); // 代表了 d:\data\projects
.
代表了当前路径..
代表了上一级路径
例如目录结构如下:
d:
|- data
|- projects
|- a
|- b
代码:
Path path = Paths.get("d:\\data\\projects\\a\\..\\b");
System.out.println(path);
System.out.println(path.normalize()); // 正常化路径
会输出:
d:\data\projects\a\..\b
d:\data\projects\b
3.4 Files
检查文件是否存在:
Path path = Paths.get("helloword/data.txt");
System.out.println(Files.exists(path));
创建一级目录:
Path path = Paths.get("helloword/d1");
Files.createDirectory(path);
- 如果目录已存在,会抛异常 FileAlreadyExistsException
- 不能一次创建多级目录,否则会抛异常 NoSuchFileException
创建多级目录用:
Path path = Paths.get("helloword/d1/d2");
Files.createDirectories(path);
拷贝文件
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/target.txt");
Files.copy(source, target);
- 如果文件已存在,会抛异常 FileAlreadyExistsException
如果希望用 source 覆盖掉 target,需要用 StandardCopyOption 来控制
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
移动文件
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/data.txt");
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
- StandardCopyOption.ATOMIC_MOVE 保证文件移动的原子性
删除文件
Path target = Paths.get("helloword/target.txt");
Files.delete(target);
- 如果文件不存在,会抛异常 NoSuchFileException
删除目录
Path target = Paths.get("helloword/d1");
Files.delete(target);
- 如果目录还有内容,会抛异常 DirectoryNotEmptyException
遍历目录文件
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
AtomicInteger dirCount = new AtomicInteger();
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
System.out.println(dir);
dirCount.incrementAndGet();
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
System.out.println(file);
fileCount.incrementAndGet();
return super.visitFile(file, attrs);
}
});
System.out.println(dirCount); // 133
System.out.println(fileCount); // 1479
}
统计 jar 的数目
Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (file.toFile().getName().endsWith(".jar")) {
fileCount.incrementAndGet();
}
return super.visitFile(file, attrs);
}
});
System.out.println(fileCount); // 724
删除多级目录
Path path = Paths.get("d:\\a");
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
Files.delete(dir);
return super.postVisitDirectory(dir, exc);
}
});
删除很危险
删除是危险操作,确保要递归删除的文件夹没有重要内容
拷贝多级目录
long start = System.currentTimeMillis();
String source = "D:\\Snipaste-1.16.2-x64";
String target = "D:\\Snipaste-1.16.2-x64aaa";
Files.walk(Paths.get(source)).forEach(path -> {
try {
String targetName = path.toString().replace(source, target);
// 是目录
if (Files.isDirectory(path)) {
Files.createDirectory(Paths.get(targetName));
}
// 是普通文件
else if (Files.isRegularFile(path)) {
Files.copy(path, Paths.get(targetName));
}
} catch (IOException e) {
e.printStackTrace();
}
});
long end = System.currentTimeMillis();
System.out.println(end - start);