Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to analyze the buffer in Java NIO

Shulou Source: shulou.com Published: 2022-05-31 22:32:20 09月30日 Update

This article shows you how to analyze the buffer in Java NIO, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

For buffers in NIO, there are a lot of content values to learn, such as buffer fragmentation and data sharing, read-only buffers and so on. Let's take a look at some of the more detailed contents of the buffer.

Allocation of buffer

In the previous examples, we have seen that when creating a buffer object, the static method allocate () is called to specify the capacity of the buffer, but calling allocate () is tantamount to creating an array of the specified size and wrapping it as a buffer object. Or we can directly wrap an existing array as a buffer object, as shown in the following sample code:

[java] view plain copy

Print?

Public class BufferWrap {

Public void myMethod ()

{

/ / allocate a buffer of the specified size

ByteBuffer buffer1 = ByteBuffer.allocate (10)

/ / Packaging an existing array

Byte array [] = new byte [10]

ByteBuffer buffer2 = ByteBuffer.wrap (array)

}

}

Buffer fragmentation

In NIO, in addition to allocating or wrapping a buffer object, you can also create a sub-buffer based on the existing buffer object, that is, cut a piece out of the existing buffer as a new buffer, but the existing buffer and the created sub-buffer are shared on the underlying array level, that is to say, the sub-buffer is equivalent to a view window of the existing buffer. Call the slice () method to create a subbuffer. Let's take a look at this with an example:

[java] view plain copy

Print?

Import java.nio.*

Public class Program {

Static public void main (String args []) throws Exception {

ByteBuffer buffer = ByteBuffer.allocate (10)

/ / data in the buffer 0-9

For (int item0; I

Tags: Buffer buffer data content method file memory object allocation array example wrapper size size regular copy change analysis that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Technology OPPO Reno MySQL MariaDB