Java ByteBuffer toString()方法及示例

Java ByteBuffer toString()方法及示例

ByteBuffer类toString() 方法是一个内置的方法,用于返回代表ByteBuffer对象所含数据的字符串。一个新的String对象被创建并初始化,以从这个ByteBuffer对象中获得字符序列,然后String被toString()方法返回。Object所包含的这个序列的后续变化不会影响String的内容。

语法

public abstract String toString()
Java

返回值: 该方法返回代表ByteBuffer对象所含数据的 字符串

以下程序说明了ByteBuffer.toString()方法:

例子1 :

// Java program to demonstrate
// toString() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the ByteBuffer
        int capacity = 5;
 
        // creating object of ByteBuffer
        // and allocating size capacity
        ByteBuffer bb1 = ByteBuffer.allocate(capacity);
 
        // putting the value in ByteBuffer
        bb1.put((byte)10);
        bb1.put((byte)20);
 
        // print the ByteBuffer
        System.out.println("Original ByteBuffer: "
                           + Arrays.toString(bb1.array()));
 
        // Creating a shared subsequence buffer of given ByteBuffer
        // using toString() method
        String value = bb1.toString();
 
        // print the ByteBuffer
        System.out.println("\nstring representation of ByteBuffer:  "
                           + value);
    }
}
Java

输出

Original ByteBuffer: [10, 20, 0, 0, 0]

string representation of ByteBuffer:  java.nio.HeapByteBuffer[pos=2 lim=5 cap=5]
Java

例2 :

// Java program to demonstrate
// toString() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the ByteBuffer
        int capacity = 4;
 
        // creating object of ByteBuffer
        // and allocating size capacity
        ByteBuffer bb1 = ByteBuffer.allocate(capacity);
 
        // putting the value in ByteBuffer
        bb1.put((byte)10)
            .put((byte)20)
            .put((byte)30)
            .put((byte)40);
 
        // print the ByteBuffer
        System.out.println("Original ByteBuffer: "
                           + Arrays.toString(bb1.array()));
 
        // Creating a shared subsequence buffer of given ByteBuffer
        // using toString() method
        String value = bb1.toString();
 
        // print the ByteBuffer
        System.out.println("\nstring representation of ByteBuffer:  "
                           + value);
    }
}
Java

输出

Original ByteBuffer: [10, 20, 30, 40]

string representation of ByteBuffer:  java.nio.HeapByteBuffer[pos=4 lim=4 cap=4]
Java

参考资料: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#toString-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册