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]
參考: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#toString–
相關用法
- Java ByteBuffer get()用法及代碼示例
- Java ByteBuffer array()用法及代碼示例
- Java ByteBuffer compact()用法及代碼示例
- Java ByteBuffer duplicate()用法及代碼示例
- Java ByteBuffer equals()用法及代碼示例
- Java ByteBuffer asDoubleBuffer()用法及代碼示例
- Java ByteBuffer asIntBuffer()用法及代碼示例
- Java ByteBuffer allocate()用法及代碼示例
- Java ByteBuffer wrap()用法及代碼示例
- Java ByteBuffer arrayOffset()用法及代碼示例
- Java ByteBuffer asLongBuffer()用法及代碼示例
- Java ByteBuffer asShortBuffer()用法及代碼示例
- Java ByteBuffer slice()用法及代碼示例
- Java ByteBuffer asCharBuffer()用法及代碼示例
- Java ByteBuffer getChar()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 ByteBuffer toString() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。