--------------------------------------------------------------------------------------------------
==Buffer.clear()==
clear this buffer. The position is set to 0, the limit is set to the capacity and the mark is discarded.
invoke this methed before using a sequence of channel-read or put operations to fill this buffer.
example:
buf.clear();
in.read(buf);
--------------------------------------------------------------------------------------------------
==Buffer.flip()==
the limit is set to the current position and then the position is set to 0. If the mark is defined then it is discarded.
after a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations.
example:
buf.put(magic);
in.read(buf);
buf.flip();
out.write(buf);
--------------------------------------------------------------------------------------------------
a example that read content from a txt file
RandomAccessFile ra=new RandomAccessFile("nio.txt","rw");
FileChannel fc=ra.getChannel();
//fc.position=0
ByteBuffer br=ByteBuffer.allocate(1024);
/*
br.position=0
br.limit=br.capacity=1024
*/
int byteRead=fc.read(br);
/*
if byteRead=10
then
fc.position=10
br.position=10
br.limit=1024
*/
while(byteRead!=-1)
{
br.flip();
/*
br.position=0
br.limit=10
*/
while(br.hasRemaining())
{
System.out.print((char)br.get());
}
/*
br.position=10
br.limit=10
*/
br.clear();
/*
br.position=0
br.limit=1024
fc.position=10
*/
byteRead=fc.read(br);
}
fc.close();