Java nio buffer (1), javanio Buffer

Source: Internet
Author: User
Tags rewind

Java nio buffer (1), javanio Buffer

This article is from my personal blog: java nio buffer (1)

We started browsing the java. nio package with the Buffer class. These classes are the basis of java. nio construction. In this series, we will follow the java NIO book to study the buffer zone, learn about different types, and learn how to use them.

A Buffer object is a fixed number of data containers. It serves as a storage space or a segmented transportation zone where data can be stored and subsequently used for retrieval.

The Genealogy of the Buffer class:

I. buffer base

1. Buffer attributes:

Capacity: The maximum number of data elements that the buffer can accommodate. This capacity is set when the buffer is created and cannot be changed.

Upper limit: the first element in the buffer zone that cannot be read or written. Or, the number of existing elements in the buffer.

Position: The next index of the element to be read or written. The position is automatically updated by the corresponding get () and put () functions.

Mark: a memo location. Call mark () to set mark = position. Call reset () to set position = mark. Undefied ).

The relationships between these four attributes are as follows:

0 <= mark <= position <= limit <= capacity

Next, let's take a look at some examples of these attributes in practical application:

Create a new ByteBuffer, as shown in the following figure:


The location is set to 0, and the capacity and upper bound are set to 10, just passing through the last byte that the buffer can accommodate. The flag is initially undefined and the capacity is fixed, but the other three attributes can be changed when the buffer is used.

2. Buffer API

Let's take a look at the following method of the Buffer class if a Buffer is used:

package java.nio;public abstract class Buffer {    public final int capacity();    public final int position();    public final Buffer position(int newPosition);    public final int limit();    public final Buffer limit(int newLimit);    public final Buffer mark();    public final Buffer reset();    public final Buffer flip();    public final Buffer rewind();    public final int remaining();    public final boolean hasRemaining();    public abstract boolean isReadOnly();}

Note that for this API, methods such as clear () should usually return void instead of Buffer reference, and these functions will be referenced and returned to them in (this) it is a class design method that allows cascade calls. Cascade calls allow this type of code:

Buffer. mark ();

Buffer. position (5 );

Buffer. reset ();

Abbreviated as buffer. mark (). position (5). reset ();

3. Access

The ASCII code representing the "Hello" string is loaded into a ByteBuffer object named buffer. The buffer result status is shown in:

Buffer. put (byte) 'H '). put (byte) 'E '). put (byte) '1 '). put (byte) '1 '). put (byte) 'O ');


Since some data has been stored in the buffer, what should we do if we want to make some changes without losing the location? The absolute put () solution can achieve this goal. Suppose we want to change the content in the buffer from the "Hello" ASCII code to "Mellow ". We can achieve this:

Buffer. put (0, (byte) 'M'). put (byte) 'W'); shows the modified buffer:

4. Flip

After we have filled the buffer, we have to clear it. We want to pass this buffer zone to a channel so that all content can be written, but if the channel now runs get () on the buffer zone (), then it will retrieve undefined data from outside the swimming data we just inserted. If we set the position to 0, the channel will get it from the correct position, but how does it know when the data we insert ends? This is the purpose of introducing the upper-bound attributes. Buffer. limit (buffer. position ()). position (0), but this kind of buffer flip from filling to releasing the turntable is designed in advance, the designer provides us with a more convenient method buffer. the flip () and flip Methods merge a buffer that can continue to add data elements into a ready to read element release state. After turning, the buffer state is shown in:

The rewind () method is similar to the flip () method, but it changes the limit value. It only sets the position value to 0, this method can be used to roll back the data that has been spent to re-read the data that has been read.

The hasRemaining method tells you whether the upper limit of the buffer has been reached, that is, limit-position = 0. The following is a method to release data elements from the buffer to an array:

For (int I = 0; buffer. hasRemaining (); I ++ {

ByteArray [I] = buffer. get ();

}

Another option is to use the remainig () method. This method tells you how many elements can be stored. You can release the buffer as follows:

Int count = buffre. remaining ();

For (int I = 0; I <count; I ++ ){

ByteArray [I] = buffer. get ();

}

5. The following is an example to fill and release the buffer:

import java.nio.CharBuffer;public class BufferFillDrain{    private static int index = 0;    private static String[] strings = {        "hello word",        "java is very beautiful",        "python is very brief"    };    public static void main(String[] args) throws Exception{        CharBuffer buffer = CharBuffer.allocate(100);        while(fillBuffer(buffer)) {            buffer.flip();            drainBuffer(buffer);            buffer.clear();        }    }        private static void drainBuffer(CharBuffer buffer) {        while(buffer.hasRemaining()) {            System.out.println(buffer.get());        }    }        private static boolean fillBuffer(CharBuffer buffer) {        if(index >= strings.length) {            String string = strings[length];            for(int i = 0; i < strings.length(); i++) {                buffer.put(string.charAt(i));            }        }        return true;    }}

6. Compression

Sometimes, we may just want to release some data from the buffer, instead of all, and then fill it again. To achieve this, unread data elements need to be moved down so that the first element index is 0, the API provides a compact () method for this. Before the buffer is released, there may be a buffer as follows:

After the buffer. compact () method is called, the buffer status is shown in:

We can see that the released bytes are removed, and the position of the released bytes is changed to limit-originPosition, and the limit parameter is set to limit = capacity. Then fill in the data from position again.

7. Comparison of Buffers

Two conditions that are considered to be the same buffer zone are from position to limit. If the data in these bytes is the same, the two buffers are the same and the comparison method is buffer. compareTo (buffer), as shown in the two buffers are the same:



Java nio Problems

Is the file channel directly mapped to the memory? If you have any Chinese characters, there must be a character-byte conversion problem. Use BufferedReader to read one row, and allocate a ByteBuffer buffer to store one row of data for processing.
 
What is java nio?

Nio is short for java New IO, a New api provided in jdk1.4. Sun officially advertised the following features:
-Buffer caching is supported for all original types.
-Character set encoding and decoding solution.
-Channel: A new original I/O abstraction.
-Supports file access interfaces for lock and memory ing files.
-Provides non-bloking non-blocking high-scalability network I/O.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.