旧I/O实现的通道之Flip_clear VS 输入输出通道联通

来源:互联网 发布:365抽奖软件破解版 编辑:程序博客网 时间:2024/04/30 06:17

Flip_clear

package com.nio;import java.io.FileInputStream;import java.io.FileOutputStream;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class Flip_clear{    public static void main(String[] args) throws Exception    {        copy("old", "new");    }    @SuppressWarnings("resource")    public static void copy(String oldFile, String newFile)        throws Exception    {        if (oldFile == null || newFile == null)        {            return;        }        FileChannel in = new FileInputStream(oldFile).getChannel(), out = new FileOutputStream(newFile).getChannel();        ByteBuffer buff = ByteBuffer.allocate(1024);// 关乎性能        while (in.read(buff) != -1)        {            buff.flip(); // Prepare for writing            out.write(buff);            buff.clear(); // Prepare for reading        }        in.close();        out.close();    }}

联通

  public static void main(String[] args)        throws Exception    {        FileChannel in = new FileInputStream("old").getChannel(), out = new FileOutputStream("new").getChannel();        in.transferTo(0, in.size(), out);        //或者  out.transferFrom(in, 0, in.size());    }
0 0
原创粉丝点击