主頁 > 後端開發 > 一分鐘搞定Netty 三大組件,如果搞不定,再看3遍

一分鐘搞定Netty 三大組件,如果搞不定,再看3遍

2022-12-29 06:24:21 後端開發

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

file

1、Selector

在使用 Selector 之前,處理 socket 連接還有以下兩種方法

使用多執行緒技術

為每個連接分別開辟一個執行緒,分別去處理對應的 socket 連接

file

這種方法存在以下幾個問題

  • 記憶體占用高
    • 每個執行緒都需要占用一定的記憶體,當連接較多時,會開辟大量執行緒,導致占用大量記憶體
  • 執行緒背景關系切換成本高
  • 只適合連接數少的場景
    • 連接數過多,會導致創建很多執行緒,從而出現問題

使用執行緒池技術

使用執行緒池,讓執行緒池中的執行緒去處理連接

file
這種方法存在以下幾個問題

  • 阻塞模式下,執行緒僅能處理一個連接
    • 執行緒池中的執行緒獲取任務(task)后,只有當其執行完任務之后(斷開連接后),才會去獲取并執行下一個任務
    • 若 socke 連接一直未斷開,則其對應的執行緒無法處理其他 socke 連接
  • 僅適合短連接場景
    • 短連接即建立連接發送請求并回應后就立即斷開,使得執行緒池中的執行緒可以快速處理其他連接

使用選擇器

selector 的作用就是配合一個執行緒來管理多個 channel(fileChannel 因為是阻塞式的,所以無法使用 selector),,獲取這些 channel 上發生的事件,這些 channel 作業在非阻塞模式下,當一個 channel 中沒有執行任務時,可以去執行其他channel 中的任務,適合連接數多,但流量較少的場景

file

若事件未就緒,呼叫 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 ,為緩沖區容量的值,

file

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

file

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

file

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

file

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

file

mark () 和 reset () 方法
  • mark () 方法會將 postion 的值保存到 mark 屬性中
  • reset () 方法會將 position 的值改為 mark 中保存的值
compact () 方法

此方法為 ByteBuffer 的方法,而不是 Buffer 的方法

  • compact 會把未讀完的資料向前壓縮,然后切換到寫模式
  • 資料前移后,原位置的值并未清零,寫時會覆寫之前的值

file

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/540855.html

標籤:Java

上一篇:Java HashMap原理

下一篇:每日演算法之求1+2+3+...+n

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more