import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelCopy {
private static final int BSIZE =1024;
public static void main(String[] args) {
try {
FileChannel in = new FileInputStream("ChannelCopy.java").getChannel(),out = new FileOutputStream("D:\\temp.txt").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
while((in.read(buffer))!=-1){
buffer.flip();//做好被写的准备
out.write(buffer);
buffer.clear();//做好被读的准备
}
} catch (FileNotFoundException e) {
System.out.println("找不到文件");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**简单写法**/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class CopyOfChannel2 {
public static void main(String[] args) {
try {
FileChannel in = new FileInputStream("ChannelCopy.java").getChannel(), out = new FileOutputStream("D:\\temp.txt").getChannel();
in.transferTo(0, in.size(), out);//简便写法
out.transferFrom(in, 0, in.size());//效果同上
} catch (FileNotFoundException e) {
System.out.println("找不到文件");
} catch (IOException e) {
e.printStackTrace();
}
}
}