Java中的 ByteBuffer toString() 方法及示例
ByteBuffer 类的toString()方法是用于返回表示 ByteBuffer 对象所包含数据的字符串的内置方法。创建并初始化一个新的 String 对象,以从该 ByteBuffer 对象中获取字符序列,然后由 toString() 返回 String。 Object 包含的此序列的后续更改不会影响 String 的内容。
句法:
public abstract String toString()
返回值:该方法返回表示 ByteBuffer 对象包含的数据的字符串。
下面的程序说明了 ByteBuffer.toString() 方法:
示例 1:
Java
// 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
// 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);
}
}
输出:
Original ByteBuffer: [10, 20, 0, 0, 0]
string representation of ByteBuffer: java.nio.HeapByteBuffer[pos=2 lim=5 cap=5]
示例 2:
Java
// 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);
}
}
输出:
Original ByteBuffer: [10, 20, 30, 40]
string representation of ByteBuffer: java.nio.HeapByteBuffer[pos=4 lim=4 cap=4]
参考: https://docs.oracle.com/javase/9/docs/api/ Java/nio/ByteBuffer.html#toString–