java

java nio의 주요 클래스인 ByteBuffer 클래스의 주요 메소드를 이해하기 위한 코드

알 수 없는 사용자 2007. 12. 13. 10:13


java nio의 주요 클래스인 ByteBuffer 클래스의 주요 메소드를 이해하기 위한 코드

src

ByteBuffer buffer = ByteBuffer.allocate(10);

buffer.put((byte) 0);
buffer.put((byte) 1);
System.out.println("put 0,1 - " + buffer + ", remain="
		+ buffer.remaining());

buffer.mark();
System.out.println("mark - " + buffer + ", remain="
		+ buffer.remaining());

buffer.put((byte) 2);
buffer.put((byte) 3);
System.out.println("put 2,3 - " + buffer + ", remain="
		+ buffer.remaining());

buffer.reset();
System.out.println("reset - " + buffer + ", remain="
		+ buffer.remaining());

buffer.flip();
System.out.println("flip - " + buffer + ", remain="
		+ buffer.remaining());

FileOutputStream fos = new FileOutputStream("c:/z/a.txt");
FileChannel fcOut = fos.getChannel();
fcOut.write(buffer);
System.out.println("write to file channel a.txt - " + buffer
		+ ", remain=" + buffer.remaining());
fcOut.close();

buffer.rewind();
System.out.println("rewind - " + buffer + ", remain="
		+ buffer.remaining());

fos = new FileOutputStream("c:/z/b.txt");
fcOut = fos.getChannel();
fcOut.write(buffer);
System.out.println("write to file channel b.txt - " + buffer
		+ ", remain=" + buffer.remaining());
fcOut.close();




result

put 0,1 - java.nio.HeapByteBuffer[pos=2 lim=10 cap=10], remain=8
mark - java.nio.HeapByteBuffer[pos=2 lim=10 cap=10], remain=8
put 2,3 - java.nio.HeapByteBuffer[pos=4 lim=10 cap=10], remain=6
reset - java.nio.HeapByteBuffer[pos=2 lim=10 cap=10], remain=8
flip - java.nio.HeapByteBuffer[pos=0 lim=2 cap=10], remain=2
write to file channel a.txt - java.nio.HeapByteBuffer[pos=2 lim=2 cap=10], remain=0
rewind - java.nio.HeapByteBuffer[pos=0 lim=2 cap=10], remain=2
write to file channel b.txt - java.nio.HeapByteBuffer[pos=2 lim=2 cap=10], remain=0