NIO's buffer [copy buffer]

[](()duplicate

--------------------------- "Analysis of Java interview questions in first-line manufacturers + back-end development study notes + latest architecture explanation video + actual project source code Lecture Notes" Free Open Source Prestige Search Official Account [Advanced Programming Road] ------------------------------------ --------

function creates a new buffer similar to the original buffer. Both buffers share data elements and have the same capacity, but each buffer has its own position, upper bound, and tag attributes. Changes made to data elements in one buffer are reflected in the other buffer. This copy buffer has the same view of the data as the original buffer. If the original buffer was read-only, or a direct buffer, the new buffer will inherit these attributes.

public static void main(String[] args) {

CharBuffer charbuffer1 = CharBuffer.allocate(10);

CharBuffer charbuffer2 = charbuffer1.duplicate();

charbuffer1.put(‘a’).put(‘b’).put(‘c’);

charbuffer1.flip();

System.out.println(charbuffer1+“–”+charbuffer1.capacity()+" “+charbuffer1.limit()+” "+charbuffer1.position());

System.out.println(charbuffer2+“–”+charbuffer2.capacity()+" “+charbuffer2.limit()+” "+charbuffer2.position());

}

output result

abc–10 3 0

abc --10 10 0

insert image description here

[](()asReadOnlyBuffer


asReadOnlyBuffer() function to generate a read-only buffer view, which is the same as duplicate(), except that this new buffer does not allow put(), and its isReadOnly() function will return true. Attempts to call put() on this read-only buffer will result in a ReadOnlyBufferException being thrown.

public static void main(String[] args) {

CharBuffer charbuffer1 = CharBuffer.allocate(10);

CharBuffer charbuffer2 = charbuffer1.asReadOnlyBuffer();

charbuffer1.put(‘a’).put(‘b’).put(‘c’);

charbuffer1.flip();

System.out.println(charbuffer1);

System.out.println(charbuffer2);

charbuffer2.put(“d”);

}

output:

abc

abc

Exception in thread “main” java.nio.ReadOnlyBufferException

at java.nio.CharBuffer.put(Unknown Source)

at java.nio.CharBuffer.put(Unknown Source)

at com.sxt.nio.Demo02.main(Demo02.java:14)

[](()slice


Guess you like

Origin blog.csdn.net/tt8889/article/details/124594130