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());
}
}
[java][nio]从ByteBuffer中获取基本数据类型
最新推荐文章于 2023-08-03 11:29:32 发布