ByteBuffer类的toString()方法是用于返回表示ByteBuffer对象包含的数据的字符串的内置方法。创建并初始化一个新的String对象,以从该ByteBuffer对象获取字符序列,然后由toString()返回String。 Object包含的对该序列的后续更改不会影响String的内容。
用法:
public abstract String toString()
返回值:此方法返回表示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 subsequance buffer of given ByteBuffer
// using toString() method
String value = bb1.toString();
// print the ByteBuffer
System.out.println("\nstring representation of ByteBuffer: "
+ value);
}
}
输出:
Original ByteBuffer: [10, 20, 0, 0, 0]
string representation of ByteBuffer: java.nio.HeapByteBuffer[pos=2 lim=5 cap=5]
示例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 subsequance buffer of given ByteBuffer
// using toString() method
String value = bb1.toString();
// print the ByteBuffer
System.out.println("\nstring representation of ByteBuffer: "
+ value);
}
}
输出:
Original ByteBuffer: [10, 20, 30, 40]
string representation of ByteBuffer: java.nio.HeapByteBuffer[pos=4 lim=4 cap=4]