[java][nio]从ByteBuffer中获取基本数据类型




import java.nio.ByteBuffer;
/**
*
* 获取基本数据类型.
*
*/
public class GetData {

private static final int BSIZE = 1024;

public static void main(String[] args) {

ByteBuffer bb = ByteBuffer.allocate(BSIZE);

int i = 0;
printBuffer(bb);

//ByteBuffer实例中每个字节自动分配为0
while(i++ < bb.limit()){
int get = bb.get();
//System.out.println("get: " + get);//get=0

if(get != 0){
System.out.println("nonzero");
}
}
System.out.println("i = " + i);//1025
printBuffer(bb);//position=1024
System.out.println("--------------");
bb.rewind();//指针移到数据头
printBuffer(bb);//position=0

//保存并读取一个字符数组
bb.asCharBuffer().put("Hello world!!");
char c ;
while((c = bb.getChar()) != 0 ){
System.out.print(c + " ");
}
printBuffer(bb);//position=28
bb.rewind();

//保存并读取一个short
bb.asShortBuffer().put((short)4583442);
System.out.println(bb.getShort());
printBuffer(bb);//position=2
bb.rewind();

//保存并读取一个int
bb.asIntBuffer().put(856522114);
System.out.println(bb.getInt());
printBuffer(bb);//position=4
bb.rewind();

//保存并读取一个long
bb.asLongBuffer().put(1286522114);
System.out.println(bb.getLong());
printBuffer(bb);//position=8
bb.rewind();

//保存并读取一个float
bb.asFloatBuffer().put(1286522114.5F);
System.out.println(bb.getFloat());
printBuffer(bb);//position=4
bb.rewind();

//保存并读取一个double
bb.asDoubleBuffer().put(1286522114.88);
System.out.println(bb.getDouble());
printBuffer(bb);//position=8
bb.rewind();

}

static void printBuffer(ByteBuffer bb){
System.out.println("limit: " + bb.limit());
System.out.println("position: " + bb.position());
System.out.println("capacity: " + bb.capacity());
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值