Java NIO Buffer

104219_GilS_2313912.png

--------------------------------------------------------------------------------------------------

==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();


转载于:https://my.oschina.net/u/2313912/blog/375140

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值