java bytebuffer 输出_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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值