好热闹

好热闹

bbbbb

Five, Sticky Bag and Half Bag Issues

  1. \n is used as a delimiter to distinguish between lines.
  2. When dealing with compact, the data that was not fully read for the first time is moved forward and integrated with the following content.

Incomplete data after \n in the read line is called a sticky package.
Incomplete data before /n in the read line is called a half package.

image

//1. Half package Sticky package
public class TestNIO10 {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(50);
        buffer.put("Hi sunshuai\nl love y".getBytes());
        doLineSplit(buffer);
        buffer.put("ou\nDo you like me?\n".getBytes());
        doLineSplit(buffer);
    }

    // Data received by ByteBuffer \n
    private static void doLineSplit(ByteBuffer buffer) {
        buffer.flip();
        for (int i = 0; i < buffer.limit(); i++) {
            if (buffer.get(i) == '\n') {
                int length = i + 1 - buffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(buffer.get());
                }

                // Cutting work completed
                target.flip();
                System.out.println("StandardCharsets.UTF_8.decode(target).toString() = " + StandardCharsets.UTF_8.decode(target).toString());
            }
        }
        buffer.compact();
    }
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.