您的位置:首页 > 其它

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

2015-12-05 17:00 267 查看
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());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  io