[java][nio]视图缓冲器


import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;

public class ViewBuffers {

	public static void main(String[] args) {
		ByteBuffer bb = ByteBuffer.wrap(new byte[]{0,0,0,0,0,0,0,'a'});
		println(bb.position());//0
		bb.rewind();
		println(bb.position());//0
		
		print("byte buffer: ");
		while(bb.hasRemaining()){
			System.out.print(bb.position() + " -> " + bb.get() + ", ");
		}
		print();
		
		CharBuffer cb = ((ByteBuffer)bb.rewind()).asCharBuffer();
		print("char buffer: ");
		while(cb.hasRemaining()){
			System.out.print(cb.position() + " -> " + cb.get() + ", ");
		}
		print();
		
		FloatBuffer fb = ((ByteBuffer)bb.rewind()).asFloatBuffer();
		print("float buffer: ");
		while(fb.hasRemaining()){
			System.out.print(fb.position() + " -> " + fb.get() + ", ");
		}
		print();
		
		IntBuffer ib = ((ByteBuffer)bb.rewind()).asIntBuffer();
		print("int buffer: ");
		while(ib.hasRemaining()){
			System.out.print(ib.position() + " -> " + ib.get() + ", ");
		}
		print();
		
		LongBuffer lb = ((ByteBuffer)bb.rewind()).asLongBuffer();
		print("Long buffer: ");
		while(lb.hasRemaining()){
			System.out.print(lb.position() + " -> " + lb.get() + ", ");
		}
		print();
		
		ShortBuffer sb = ((ByteBuffer)bb.rewind()).asShortBuffer();
		print("short buffer: ");
		while(sb.hasRemaining()){
			System.out.print(sb.position() + " -> " + sb.get() + ", ");
		}
		print();
		
		DoubleBuffer db = ((ByteBuffer)bb.rewind()).asDoubleBuffer();
		print("double buffer: ");
		while(db.hasRemaining()){
			System.out.print(db.position() + " -> " + db.get() + ", ");
		}
		print();
		

	}
	
	static void print(Object o){
		System.out.print(o);
	}
	
	static void println(Object o){
		System.out.println(o);
	}
	
	static void print(){
		System.out.println();
	}

}
/*
0
0
byte buffer: 0 -> 0, 1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0, 5 -> 0, 6 -> 0, 7 -> 97, 
char buffer: 0 ->   , 1 -> , 2 -> , 3 -> a, 
float buffer: 0 -> 0.0, 1 -> 1.36E-43, 
int buffer: 0 -> 0, 1 -> 97, 
Long buffer: 0 -> 97, 
short buffer: 0 -> 0, 1 -> 0, 2 -> 0, 3 -> 97, 
double buffer: 0 -> 4.8E-322, 


*/

你可能感兴趣的:(java)