当前位置: 首页>>代码示例>>用法及示例精选>>正文


Java - ByteBuffer toString()用法及代码示例

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–



相关用法

注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 ByteBuffer toString() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。