📜  Java的.nio.Buffer类在Java中

📅  最后修改于: 2022-05-13 01:55:17.491000             🧑  作者: Mango

Java的.nio.Buffer类在Java中

Buffer类为特定原始类型的数据块提供缓冲区或容器。元素的有限序列线性存储在缓冲区中。

缓冲区的重要属性可以方便地在数据中执行读写操作:

  • 容量:此属性确定缓冲区中可以存在的最大元素数。
  • 限制:该属性通过提供元素的索引来确定可以读取或写入的数据的限制。
  • 位置:此属性确定当前元素在缓冲区中的位置。

语法:类声明

public abstract class Buffer extends Object

Buffer 类为以下每种缓冲区数据类型提供了一个子类,例如 ByteBuffer、MappedByteBuffer、CharBuffer、DoubleBuffer、FloatBuffer、IntBuffer、LongBuffer、ShortBuffer。 Buffer类继承了Java.lang.Object类的clone()、finalize()、getClass()、hashCode()、notify()、notifyAll()、toString()、wait()等方法。现在,继续介绍 Buffer 类的方法,如下表所示,按字母顺序显示:

MethodDescription
array()This method returns the array that backs this buffer
arrayOffset()This method returns the offset within this buffer’s backing array of the first element of the buffer 
capacity()This method returns this buffer’s capacity.
clear()This method clears this buffer.
flip()This method flips this buffer.
hasArray()This method tells whether or not this buffer is backed by an accessible array.
hasRemaining()This method tells whether there are any elements between the current position and the limit.
isDirect()This method tells whether or not this buffer is direct.
isReadOnly()This method tells whether or not this buffer is read-only.
limit()This method returns this buffer’s limit.
limit(int newLimit)This method sets this buffer’s limit.
mark()This method sets this buffer’s mark at its position.
position()This method returns this buffer’s position.
position(int newPosition)This method sets this buffer’s position.
remaining()This method returns the number of elements between the current position and the limit.
reset()This method resets this buffer’s position to the previously marked position.
rewind()This method rewinds this buffer.

实现: Buffer类及其方法



示例 1

Java
// Java program to demonstrate Buffer Class
 
// Importing required libraries
import java.nio.*;
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring the capacity of the ByteBuffer
        int capacity = 5;
 
        // Try block to check for exceptions
        try {
 
            // Creating the ByteBuffer
 
            // Creating object of ByteBuffer class and
            // allocating size capacity
            ByteBuffer bufferObj
                = ByteBuffer.allocate(capacity);
 
            // Putting the int to byte typecast
            // value in ByteBuffer using put() method
 
            // Custom input entries
            bufferObj.put((byte)10);
            bufferObj.put((byte)20);
            bufferObj.put((byte)30);
            bufferObj.put((byte)40);
            bufferObj.put((byte)50);
 
            // Typecasting ByteBuffer into Buffer
            Buffer bufferObj1 = (Buffer)bufferObj;
 
            // Getting array that backs this buffer
            // using array() method
            byte[] arr = (byte[])bufferObj1.array();
 
            // Display message only
            System.out.print(" The array is : [");
 
            // Print the array
            for (int i = 0; i < arr.length; i++)
                System.out.print(" " + arr[i]);
            System.out.print(" ]");
        }
 
        // Catch block to handle the exception
        catch (ReadOnlyBufferException e) {
 
            // Print message where exception occured
            // is displayed on console
            System.out.println("Exception throws: " + e);
        }
    }
}


Java
// Java program to demonstrate Buffer class
 
// Importing required libraries
import java.nio.*;
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // try block to check for exceptions
        try {
 
            // Creating and initializing byte array
            // with custom elements
            byte[] barr = { 10, 20, 30, 40, 50 };
 
            // Creating object of ByteBuffer class
            // and allocating size capacity
            ByteBuffer bufferObj = ByteBuffer.wrap(barr);
 
            // Typecasting ByteBuffer into Buffer
            Buffer bufferObj1 = (Buffer)bufferObj;
 
            // now trying to set the position at index 2
            bufferObj1.position(2);
 
            // Setting this buffer mark position
            // using mark() method
            bufferObj1.mark();
 
            // Again trying to set the position at index 4
            bufferObj1.position(5);
 
            // Display the position
            System.out.println("position before reset: "
                               + bufferObj1.position());
 
            // Now trying to call clear() to restore
            // to the position at index 0 by discarding the
            // mark
            bufferObj1.clear();
 
            // Print aand display the position
            System.out.println("position after reset: "
                               + bufferObj1.position());
        }
 
        // Catch block to handle the exception
        catch (InvalidMarkException e) {
 
            // Display message to be showcase when exception
            // occured
            System.out.println(
                "new position is less than "
                + "the position we marked before ");
 
            // Print the exception on the console
            // along with display message
            System.out.println("Exception throws: " + e);
        }
    }
}


输出
The array is : [ 10 20 30 40 50 ]

示例 2

Java

// Java program to demonstrate Buffer class
 
// Importing required libraries
import java.nio.*;
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // try block to check for exceptions
        try {
 
            // Creating and initializing byte array
            // with custom elements
            byte[] barr = { 10, 20, 30, 40, 50 };
 
            // Creating object of ByteBuffer class
            // and allocating size capacity
            ByteBuffer bufferObj = ByteBuffer.wrap(barr);
 
            // Typecasting ByteBuffer into Buffer
            Buffer bufferObj1 = (Buffer)bufferObj;
 
            // now trying to set the position at index 2
            bufferObj1.position(2);
 
            // Setting this buffer mark position
            // using mark() method
            bufferObj1.mark();
 
            // Again trying to set the position at index 4
            bufferObj1.position(5);
 
            // Display the position
            System.out.println("position before reset: "
                               + bufferObj1.position());
 
            // Now trying to call clear() to restore
            // to the position at index 0 by discarding the
            // mark
            bufferObj1.clear();
 
            // Print aand display the position
            System.out.println("position after reset: "
                               + bufferObj1.position());
        }
 
        // Catch block to handle the exception
        catch (InvalidMarkException e) {
 
            // Display message to be showcase when exception
            // occured
            System.out.println(
                "new position is less than "
                + "the position we marked before ");
 
            // Print the exception on the console
            // along with display message
            System.out.println("Exception throws: " + e);
        }
    }
}
输出
position before reset: 5
position after reset: 0