nio基本使用

来源:互联网 发布:伽罗瓦理论知乎 编辑:程序博客网 时间:2024/05/29 12:03

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



原创粉丝点击