nio基本使用

nio速度的提高来自于所使用的结构更接近于操作系统执行I/O的方式:通道和缓冲器。我们可以把它想象成一个煤矿,

通道是一个包含煤层(数据)的矿藏,而缓冲器则是派送到矿藏的卡车。卡车载满煤炭而归,我们再从卡车上获得煤炭。

也就是说,我们并没有直接和通道交互,我们只是和缓冲器交互,并且把缓冲器派送到通道。通道要么从缓冲器获取数据,

要么向缓冲器发送数据。

唯一直接与通道交互的缓冲器是ByteBuffer。还有一个方法选择集,用于以原始的字节形式或基本数据类型输出或读取数据。

但是没有办法输出或读取对象,即使是字符串对象也不行。

旧i/o中的FileInputStream、FileOutputStream以及RandomAccessFile被修改了,可以产生FileChannel(通道)。Reader和

Writer这种字符模式类不能用于产生通道;但是Channels类提供了实用方法,用以在通道中产生Reader和Writer。

实例演示上面三种基本类型的流:

public class GetChannel {
    private static final int BSIZE=1024;
    public static void main(String[] args) throws Exception{
        FileChannel fc=new FileOutputStream("data.txt").getChannel();//获得通道
        fc.write(ByteBuffer.wrap("Some text".getBytes()));//往缓冲器中写数据,并写入通道
        fc.close();
        fc=new RandomAccessFile("data.txt","rw").getChannel();//获取可读写的通道
        fc.position(fc.size());//Move to the end.
        fc.write(ByteBuffer.wrap("Some more".getBytes()));
        fc.close();
        fc=new FileInputStream("data.txt").getChannel();
        ByteBuffer buff=ByteBuffer.allocate(BSIZE);//缓冲区大小
        fc.read(buff);//往缓冲器中写入数据
        buff.flip();//必须调用缓冲器上的flip(),让它做好让别人读取字节的准备。
        while (buff.hasRemaining()){
            System.out.print((char)buff.get());
        }
    }
}

如果我们打算实用缓冲器执行进一步的read()操作,我们也必须得调用clear()来为每个read()做好准备:

public class ChannelCopy {
    private static final int BSIZE=1024;
    public static void main(String[] args) throws Exception{
        FileChannel in=new FileInputStream("data.txt").getChannel(),
                out=new FileOutputStream("data1.txt").getChannel();
        ByteBuffer buffer=ByteBuffer.allocate(BSIZE);
        while (in.read(buffer)!=-1){
            buffer.flip();//等待被读取
            out.write(buffer);
            buffer.clear();//等待下一次存入数据
        }
    }
}
可以用特殊方法transferTo()和transferFrom()将一个通道和另一个通道直接相连:

public class TransferTo {
    public static void main(String[] args) throws Exception {
        FileChannel in = new FileInputStream("data.txt").getChannel(),
                out = new FileOutputStream("data2.txt").getChannel();
        in.transferTo(0, in.size(), out);
        //Or:
        //out.transferFrom(in,0,in.size());
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值