1. 三大組件簡介
Channel 與 Buffer
Java NIO 系統的核心在于:通道 (Channel) 和緩沖區 (Buffer),通道表示打開到 IO 設備 (例如:檔案、套接字) 的連接,若需要使用 NIO 系統,需要獲取用于連接 IO 設備的通道 以及用于容納資料的緩沖區,然后操作緩沖區,對資料進行處理
簡而言之,通道負責傳輸,緩沖區負責存盤
常見的 Channel 有以下四種,其中 FileChannel 主要用于檔案傳輸,其余三種用于網路通信
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
Buffer 有以下幾種,其中使用較多的是 ByteBuffer
-
ByteBuffer
- MappedByteBuffer
- DirectByteBuffer
- HeapByteBuffer
-
ShortBuffer
-
IntBuffer
-
LongBuffer
-
FloatBuffer
-
DoubleBuffer
-
CharBuffer

1、Selector
在使用 Selector 之前,處理 socket 連接還有以下兩種方法
使用多執行緒技術
為每個連接分別開辟一個執行緒,分別去處理對應的 socket 連接

這種方法存在以下幾個問題
- 記憶體占用高
- 每個執行緒都需要占用一定的記憶體,當連接較多時,會開辟大量執行緒,導致占用大量記憶體
- 執行緒背景關系切換成本高
- 只適合連接數少的場景
- 連接數過多,會導致創建很多執行緒,從而出現問題
使用執行緒池技術
使用執行緒池,讓執行緒池中的執行緒去處理連接

這種方法存在以下幾個問題
- 阻塞模式下,執行緒僅能處理一個連接
- 執行緒池中的執行緒獲取任務(task)后,只有當其執行完任務之后(斷開連接后),才會去獲取并執行下一個任務
- 若 socke 連接一直未斷開,則其對應的執行緒無法處理其他 socke 連接
- 僅適合短連接場景
- 短連接即建立連接發送請求并回應后就立即斷開,使得執行緒池中的執行緒可以快速處理其他連接
使用選擇器
selector 的作用就是配合一個執行緒來管理多個 channel(fileChannel 因為是阻塞式的,所以無法使用 selector),,獲取這些 channel 上發生的事件,這些 channel 作業在非阻塞模式下,當一個 channel 中沒有執行任務時,可以去執行其他channel 中的任務,適合連接數多,但流量較少的場景

若事件未就緒,呼叫 selector 的 select () 方法會阻塞執行緒,直到 channel 發生了就緒事件,這些事件就緒后,select 方法就會回傳這些事件交給 thread 來處理
2、ByteBuffer
使用案例
使用方式
-
向 buffer 寫入資料,例如呼叫 channel.read (buffer)
-
呼叫 flip () 切換至
讀模式
- flip 會使得 buffer 中的 limit 變為 position,position 變為 0
-
從 buffer 讀取資料,例如呼叫 buffer.get ()
-
呼叫 clear () 或者 compact () 切換至
寫模式
- 呼叫 clear () 方法時 position=0,limit 變為 capacity
- 呼叫 compact () 方法時,會將緩沖區中的未讀資料壓縮到緩沖區前面
-
重復以上步驟
使用 ByteBuffer 讀取檔案中的內容
public class TestByteBuffer {
public static void main(String[] args) {
try (FileChannel channel = new FileInputStream("stu.txt").getChannel()){
//給緩沖區 分配空間
ByteBuffer buffer = ByteBuffer.allocate(10);
int read = 0 ;
StringBuilder builder = new StringBuilder();
while ((read =channel.read(buffer))>0){
//切換成 讀模式 limit = position; position=0
buffer.flip();
while (buffer.hasRemaining()){
builder.append((char)buffer.get());
}
//清空位元組陣列 切換成 寫模式 position=0 ;limit = capacity
buffer.clear();
}
System.out.println(builder.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
列印結果:
0123456789abcdef
核心屬性
位元組緩沖區的父類 Buffer 中有幾個核心屬性,如下
// Invariants: mark <= position <= limit <= capacity
private int mark = -1;
private int position = 0;
private int limit;
private int capacity;
- capacity:緩沖區的容量,通過建構式賦予,一旦設定,無法更改
- limit:緩沖區的界限,位于 limit 后的資料不可讀寫,緩沖區的限制不能為負,并且 不能大于其容量
- position: 下一個讀寫位置的索引(類似 PC),緩沖區的位置不能為負,并且不能大于 limit
- mark:記錄當前 position 的值,position 被改變后,可以通過呼叫 reset () 方法恢復到 mark 的位置,
以上四個屬性必須滿足以下要求
mark <= position <= limit <= capacity
核心方法
put () 方法
- put () 方法可以將一個資料放入到緩沖區中,
- 進行該操作后,postition 的值會 +1,指向下一個可以放入的位置,capacity = limit ,為緩沖區容量的值,

flip () 方法
- flip () 方法會 切換對緩沖區的操作模式 ,由 寫 -> 讀 / 讀 -> 寫
- 進行該操作后
- 如果是 寫模式 -> 讀模式,position = 0 , limit 指向最后一個元素的下一個位置,capacity 不變
- 如果是讀 -> 寫 ,則恢復為 put () 方法中的值

get () 方法
- get () 方法會讀取緩沖區中的一個值
- 進行該操作后,position 會 +1 ,如果超過了 limit 則會拋出例外
- 注意:get (i) 方法不會改變 position 的值

rewind () 方法
- 該方法 只能在讀模式下使用
- rewind () 方法后,會恢復 position、limit 和 capacity 的值,變為進行 get () 前的值

clear () 方法
- clear () 方法會將緩沖區中的各個屬性恢復為最初的狀態,position = 0, capacity = limit
- 此時緩沖區的資料依然存在,處于 “被遺忘” 狀態,下次進行寫操作時會覆寫這些資料

mark () 和 reset () 方法
- mark () 方法會將 postion 的值保存到 mark 屬性中
- reset () 方法會將 position 的值改為 mark 中保存的值
compact () 方法
此方法為 ByteBuffer 的方法,而不是 Buffer 的方法
- compact 會把未讀完的資料向前壓縮,然后切換到寫模式
- 資料前移后,原位置的值并未清零,寫時會覆寫之前的值

clear() VS compact()
clear 只是對 position、limit、mark 進行重置,而 compact 在對 position 進行設定,以及 limit、mark 進行重置的同時,還涉及到資料在記憶體中拷貝(會呼叫 array),所以 compact 比 clear 更耗性能,但 compact 能保存你未讀取的資料,將新資料追加到為讀取的資料之后;而 clear 則不行,若你呼叫了 clear,則未讀取的資料就無法再讀取到了
所以需要根據情況來判斷使用哪種方法進行模式切換
方法呼叫及演示
ByteBuffer 除錯工具類
需要先匯入 netty 依賴
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.51.Final</version>
</dependency>
import java.nio.ByteBuffer;
import io.netty.util.internal.MathUtil;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.MathUtil.*;
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(StringUtil.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);
}
private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
if (MathUtil.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(
" +-------------------------------------------------+" +
StringUtil.NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" +
StringUtil.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(StringUtil.NEWLINE +
"+--------+-------------------------------------------------+----------------+");
}
private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
if (row < HEXDUMP_ROWPREFIXES.length) {
dump.append(HEXDUMP_ROWPREFIXES[row]);
} else {
dump.append(StringUtil.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);
}
}
呼叫 ByteBuffer 的方法
public class TestByteBuffer {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
// 向buffer中寫入1個位元組的資料
buffer.put((byte)97);
// 使用工具類,查看buffer狀態
ByteBufferUtil.debugAll(buffer);
// 向buffer中寫入4個位元組的資料
buffer.put(new byte[]{98, 99, 100, 101});
ByteBufferUtil.debugAll(buffer);
// 獲取資料
buffer.flip();
ByteBufferUtil.debugAll(buffer);
System.out.println(buffer.get());
System.out.println(buffer.get());
ByteBufferUtil.debugAll(buffer);
// 使用compact切換模式
buffer.compact();
ByteBufferUtil.debugAll(buffer);
// 再次寫入
buffer.put((byte)102);
buffer.put((byte)103);
ByteBufferUtil.debugAll(buffer);
}
}
運行結果
// 向緩沖區寫入了一個位元組的資料,此時postition為1
+--------+-------------------- 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......... |
+--------+-------------------------------------------------+----------------+
// 向緩沖區寫入四個位元組的資料,此時position為5
+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 65 00 00 00 00 00 |abcde..... |
+--------+-------------------------------------------------+----------------+
// 呼叫flip切換模式,此時position為0,表示從第0個資料開始讀取
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [5]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 65 00 00 00 00 00 |abcde..... |
+--------+-------------------------------------------------+----------------+
// 讀取兩個位元組的資料
97
98
// position變為2
+--------+-------------------- all ------------------------+----------------+
position: [2], limit: [5]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 65 00 00 00 00 00 |abcde..... |
+--------+-------------------------------------------------+----------------+
// 呼叫compact切換模式,此時position及其后面的資料被壓縮到ByteBuffer前面去了
// 此時position為3,會覆寫之前的資料
+--------+-------------------- all ------------------------+----------------+
position: [3], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 63 64 65 64 65 00 00 00 00 00 |cdede..... |
+--------+-------------------------------------------------+----------------+
// 再次寫入兩個位元組的資料,之前的 0x64 0x65 被覆寫
+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 63 64 65 66 67 00 00 00 00 00 |cdefg..... |
+--------+-------------------------------------------------+----------------+
字串與 ByteBuffer 的相互轉換
方法一
編碼:字串呼叫 getByte 方法獲得 byte 陣列,將 byte 陣列放入 ByteBuffer 中
解碼:先呼叫 ByteBuffer 的 flip 方法,然后通過 StandardCharsets 的 decoder 方法解碼
public class Translate {
public static void main(String[] args) {
// 準備兩個字串
String str1 = "hello";
String str2 = "";
ByteBuffer buffer1 = ByteBuffer.allocate(16);
// 通過字串的getByte方法獲得位元組陣列,放入緩沖區中
buffer1.put(str1.getBytes());
ByteBufferUtil.debugAll(buffer1);
// 將緩沖區中的資料轉化為字串
// 切換模式
buffer1.flip();
// 通過StandardCharsets解碼,獲得CharBuffer,再通過toString獲得字串
str2 = StandardCharsets.UTF_8.decode(buffer1).toString();
System.out.println(str2);
ByteBufferUtil.debugAll(buffer1);
}
}
運行結果
+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [16]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 |hello...........|
+--------+-------------------------------------------------+----------------+
hello
+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [5]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 |hello...........|
+--------+-------------------------------------------------+----------------+
方法二
編碼:通過 StandardCharsets 的 encode 方法獲得 ByteBuffer,此時獲得的 ByteBuffer 為讀模式,無需通過 flip 切換模式
解碼:通過 StandardCharsets 的 decoder 方法解碼
public class Translate {
public static void main(String[] args) {
// 準備兩個字串
String str1 = "hello";
String str2 = "";
// 通過StandardCharsets的encode方法獲得ByteBuffer
// 此時獲得的ByteBuffer為讀模式,無需通過flip切換模式
ByteBuffer buffer1 = StandardCharsets.UTF_8.encode(str1);
ByteBufferUtil.debugAll(buffer1);
// 將緩沖區中的資料轉化為字串
// 通過StandardCharsets解碼,獲得CharBuffer,再通過toString獲得字串
str2 = StandardCharsets.UTF_8.decode(buffer1).toString();
System.out.println(str2);
ByteBufferUtil.debugAll(buffer1);
}
}
運行結果
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [5]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f |hello |
+--------+-------------------------------------------------+----------------+
hello
+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [5]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f |hello |
+--------+-------------------------------------------------+----------------+
方法三
編碼:字串呼叫 getByte () 方法獲得位元組陣列,將位元組陣列傳給 ByteBuffer 的 wrap () 方法,通過該方法獲得 ByteBuffer,同樣無需呼叫 flip 方法切換為讀模式
解碼:通過 StandardCharsets 的 decoder 方法解碼
public class Translate {
public static void main(String[] args) {
// 準備兩個字串
String str1 = "hello";
String str2 = "";
// 通過StandardCharsets的encode方法獲得ByteBuffer
// 此時獲得的ByteBuffer為讀模式,無需通過flip切換模式
ByteBuffer buffer1 = ByteBuffer.wrap(str1.getBytes());
ByteBufferUtil.debugAll(buffer1);
// 將緩沖區中的資料轉化為字串
// 通過StandardCharsets解碼,獲得CharBuffer,再通過toString獲得字串
str2 = StandardCharsets.UTF_8.decode(buffer1).toString();
System.out.println(str2);
ByteBufferUtil.debugAll(buffer1);
}
}
運行結果
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [5]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f |hello |
+--------+-------------------------------------------------+----------------+
hello
+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [5]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f |hello |
+--------+-------------------------------------------------+----------------+
粘包與半包
現象
網路上有多條資料發送給服務端,資料之間使用 \n 進行分隔
但由于某種原因這些資料在接收時,被進行了重新組合,例如原始資料有 3 條為
- Hello,world\n
- I’m Nyima\n
- How are you?\n
變成了下面的兩個 byteBuffer (粘包,半包)
- Hello,world\nI’m Nyima\nHo
- w are you?\n
出現原因
粘包
發送方 在發送資料時,并不是一條一條地發送資料,而是將資料整合在一起,當資料達到一定的數量后再一起發送,這就會導致多條資訊被放在一個緩沖區中被一起發送出去
半包
接收方 的緩沖區的大小是有限的,當接收方的緩沖區滿了以后,就需要將資訊截斷,等緩沖區空了以后再繼續放入資料,這就會發生一段完整的資料最后被截斷的現象
解決辦法
-
通過 get (index) 方法遍歷 ByteBuffer,遇到分隔符時進行處理,
注意
:get (index) 不會改變 position 的值
- 記錄該段資料長度,以便于申請對應大小的緩沖區
- 將緩沖區的資料通過 get () 方法寫入到 target 中
-
呼叫 compact 方法切換模式,因為緩沖區中可能還有未讀的資料
public class ByteBufferDemo {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(32);
// 模擬粘包+半包
buffer.put("Hello,world\nI'm Nyima\nHo".getBytes());
// 呼叫split函式處理
split(buffer);
buffer.put("w are you?\n".getBytes());
split(buffer);
}
private static void split(ByteBuffer buffer) {
// 切換為讀模式
buffer.flip();
for(int i = 0; i < buffer.limit(); i++) {
// 遍歷尋找分隔符
// get(i)不會移動position
if (buffer.get(i) == '\n') {
// 緩沖區長度
int length = i+1-buffer.position();
ByteBuffer target = ByteBuffer.allocate(length);
// 將前面的內容寫入target緩沖區
for(int j = 0; j < length; j++) {
// 將buffer中的資料寫入target中
target.put(buffer.get());
}
// 列印查看結果
ByteBufferUtil.debugAll(target);
}
}
// 切換為寫模式,但是緩沖區可能未讀完,這里需要使用compact
buffer.compact();
}
}
運行結果
+--------+-------------------- all ------------------------+----------------+
position: [12], limit: [12]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 48 65 6c 6c 6f 2c 77 6f 72 6c 64 0a |Hello,world. |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [10], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 49 27 6d 20 4e 79 69 6d 61 0a |I'm Nyima. |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [13], limit: [13]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 48 6f 77 20 61 72 65 20 79 6f 75 3f 0a |How are you?. |
+--------+-------------------------------------------------+----------------+
3、FileChannel
作業模式
FileChannel 只能在阻塞模式下作業,所以無法搭配 Selector
獲取
不能直接打開 FileChannel,必須通過 FileInputStream、FileOutputStream 或者 RandomAccessFile 來獲取 FileChannel,它們都有 getChannel 方法
- 通過 FileInputStream 獲取的 channel 只能讀
- 通過 FileOutputStream 獲取的 channel 只能寫
- 通過 RandomAccessFile 是否能讀寫 根據構造 RandomAccessFile 時的讀寫模式決定
讀取
通過 FileInputStream 獲取 channel,通過 read 方法將資料寫入到 ByteBuffer 中
read 方法的回傳值表示讀到了多少位元組,若讀到了檔案末尾則回傳 - 1
int readBytes = channel.read(buffer);
可根據回傳值判斷是否讀取完畢
while(channel.read(buffer) > 0) {
// 進行對應操作
...
}
寫入
因為 channel 也是有大小的,所以 write 方法并不能保證一次將 buffer 中的內容全部寫入 channel,必須需要按照以下規則進行寫入
// 通過hasRemaining()方法查看緩沖區中是否還有資料未寫入到通道中
while(buffer.hasRemaining()) {
channel.write(buffer);
}
關閉
通道需要 close,一般情況通過 try-with-resource 進行關閉,最好使用以下方法獲取 strea 以及 channel,避免某些原因使得資源未被關閉
public class TestChannel {
public static void main(String[] args) throws IOException {
try (FileInputStream fis = new FileInputStream("stu.txt");
FileOutputStream fos = new FileOutputStream("student.txt");
FileChannel inputChannel = fis.getChannel();
FileChannel outputChannel = fos.getChannel()) {
// 執行對應操作
...
}
}
}
位置
position
channel 也擁有一個保存讀取資料位置的屬性,即 position
long pos = channel.position();
可以通過 position (int pos) 設定 channel 中 position 的值
long newPos = ...;
channel.position(newPos);
設定當前位置時,如果設定為檔案的末尾
- 這時讀取會回傳 -1
- 這時寫入,會追加內容,但要注意如果 position 超過了檔案末尾,再寫入時在新內容和原末尾之間會有空洞(00)
強制寫入
作業系統出于性能的考慮,會將資料快取,不是立刻寫入磁盤,而是等到快取滿了以后將所有資料一次性的寫入磁盤,可以呼叫 force(true) 方法將檔案內容和元資料(檔案的權限等資訊)立刻寫入磁盤
2、兩個 Channel 傳輸資料
transferTo 方法
使用 transferTo 方法可以快速、高效地將一個 channel 中的資料傳輸到另一個 channel 中,但一次只能傳輸 2G 的內容
transferTo 底層使用了零拷貝技術
public class TestChannel {
public static void main(String[] args){
try (FileInputStream fis = new FileInputStream("stu.txt");
FileOutputStream fos = new FileOutputStream("student.txt");
FileChannel inputChannel = fis.getChannel();
FileChannel outputChannel = fos.getChannel()) {
// 引數:inputChannel的起始位置,傳輸資料的大小,目的channel
// 回傳值為傳輸的資料的位元組數
// transferTo一次只能傳輸2G的資料
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
} catch (IOException e) {
e.printStackTrace();
}
}
}
當傳輸的檔案大于 2G 時,需要使用以下方法進行多次傳輸
public class TestChannel {
public static void main(String[] args){
try (FileInputStream fis = new FileInputStream("stu.txt");
FileOutputStream fos = new FileOutputStream("student.txt");
FileChannel inputChannel = fis.getChannel();
FileChannel outputChannel = fos.getChannel()) {
long size = inputChannel.size();
long capacity = inputChannel.size();
// 分多次傳輸
while (capacity > 0) {
// transferTo回傳值為傳輸了的位元組數
capacity -= inputChannel.transferTo(size-capacity, capacity, outputChannel);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、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
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,需要用 StandardOption 來控制
Files.copy(source, target, StandardOption.REPLACE_EXISTING);
移動檔案
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/data.txt");
Files.move(source, target, StandardOption.ATOMIC_MOVE);
- StandardOption.ATOMIC_MOVE 保證檔案移動的原子性
洗掉
洗掉檔案
Path target = Paths.get("helloword/target.txt");
Files.delete(target);
- 如果檔案不存在,會拋例外 NoSuchFileException
洗掉目錄
Path target = Paths.get("helloword/d1");
Files.delete(target);
- 如果目錄還有內容,會拋例外 DirectoryNotEmptyException
遍歷
可以使用 Files 工具類中的 walkFileTree (Path, FileVisitor) 方法,其中需要傳入兩個引數
-
Path:檔案起始路徑
-
FileVisitor:檔案訪問器,
使用訪問者模式
-
介面的實作類
SimpleFileVisitor
有四個方法
- preVisitDirectory:訪問目錄前的操作
- visitFile:訪問檔案的操作
- visitFileFailed:訪問檔案失敗時的操作
- postVisitDirectory:訪問目錄后的操作
-
public class TestFiles {
public static void main(String[] args) throws IOException {
AtomicInteger ditCount = new AtomicInteger();
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(Paths.get("D:\\Program Files\\jdk7"),new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
System.err.println("=====>"+dir);
ditCount.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("dir count :"+ditCount);
System.out.println("file count :"+fileCount);
}
}
運行結果如下
...
=====>D:\Program Files\jdk7\jre7\lib\zi\SystemV\EST5EDT
=====>D:\Program Files\jdk7\jre7\lib\zi\SystemV\HST10
=====>D:\Program Files\jdk7\jre7\lib\zi\SystemV\MST7
=====>D:\Program Files\jdk7\jre7\lib\zi\SystemV\MST7MDT
=====>D:\Program Files\jdk7\jre7\lib\zi\SystemV\PST8
=====>D:\Program Files\jdk7\jre7\lib\zi\SystemV\PST8PDT
=====>D:\Program Files\jdk7\jre7\lib\zi\SystemV\YST9
=====>D:\Program Files\jdk7\jre7\lib\zi\SystemV\YST9YDT
=====>D:\Program Files\jdk7\jre7\lib\zi\WET
=====>D:\Program Files\jdk7\jre7\lib\zi\ZoneInfoMappings
=====>D:\Program Files\jdk7\jre7\LICENSE
=====>D:\Program Files\jdk7\jre7\README.txt
=====>D:\Program Files\jdk7\jre7\release
=====>D:\Program Files\jdk7\jre7\THIRDPARTYLICENSEREADME-JAVAFX.txt
=====>D:\Program Files\jdk7\jre7\THIRDPARTYLICENSEREADME.txt
=====>D:\Program Files\jdk7\jre7\Welcome.html
dir count :183
file count :2437
本文由
傳智教育博學谷教研團隊發布,如果本文對您有幫助,歡迎
關注和點贊;如果您有任何建議也可留言評論或私信,您的支持是我堅持創作的動力,轉載請注明出處!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/540872.html
標籤:其他
