一、CreateBuffer
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class CreateBuffer
{
static public void main( String args[] ) throws Exception {
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
buffer.put( (byte)'a' );
buffer.put( (byte)'b' );
buffer.put( (byte)'c' );
buffer.flip();
System.out.println( (char)buffer.get() );
System.out.println( (char)buffer.get() );
System.out.println( (char)buffer.get() );
}
}
二、CreateArrayBuffer
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class CreateArrayBuffer
{
static public void main( String args[] ) throws Exception {
byte array[] = new byte[1024];
ByteBuffer buffer = ByteBuffer.wrap( array );
buffer.put( (byte)'a' );
buffer.put( (byte)'b' );
buffer.put( (byte)'c' );
buffer.flip();
System.out.println( (char)buffer.get() );
System.out.println( (char)buffer.get() );
System.out.println( (char)buffer.get() );
}
}
三、SliceBuffer
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class SliceBuffer
{
static public void main( String args[] ) throws Exception {
ByteBuffer buffer = ByteBuffer.allocate( 10 );
for (int i=0; i<buffer.capacity(); ++i) {
buffer.put( (byte)i );
}
buffer.position( 3 );
buffer.limit( 7 );
ByteBuffer slice = buffer.slice();
for (int i=0; i<slice.capacity(); ++i) {
byte b = slice.get( i );
b *= 11;
slice.put( i, b );
}
buffer.position( 0 );
buffer.limit( buffer.capacity() );
while (buffer.remaining()>0) {
System.out.println( buffer.get() );
}
}
}
四、TypesInByteBuffer
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class TypesInByteBuffer
{
static public void main( String args[] ) throws Exception {
ByteBuffer buffer = ByteBuffer.allocate( 64 );
buffer.putInt( 30 );
buffer.putLong( 7000000000000L );
buffer.putDouble( Math.PI );
buffer.flip();
System.out.println( buffer.getInt() );
System.out.println( buffer.getLong() );
System.out.println( buffer.getDouble() );
}
}
五、UseFloatBuffer
import java.nio.*;
public class UseFloatBuffer
{
static public void main( String args[] ) throws Exception {
FloatBuffer buffer = FloatBuffer.allocate( 10 );
for (int i=0; i<buffer.capacity(); ++i) {
float f = (float)Math.sin( (((float)i)/10)*(2*Math.PI) );
buffer.put( f );
}
buffer.flip();
while (buffer.hasRemaining()) {
float f = buffer.get();
System.out.println( f );
}
}
}
六、WriteSomeBytes
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class WriteSomeBytes
{
static private final byte message[] = { 83, 111, 109, 101, 32,
98, 121, 116, 101, 115, 46 };
static public void main( String args[] ) throws Exception {
FileOutputStream fout = new FileOutputStream( "writesomebytes.txt" );
FileChannel fc = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
for (int i=0; i<message.length; ++i) {
buffer.put( message[i] );
}
buffer.flip();
fc.write( buffer );
fout.close();
}
}