package cn.com.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class CopyFile {
/**
* NIO实现的文件复制功能
* @param sourceFile 源文件路径
* @param targetFile 目标文件路径
*/
public void readerFile(String sourceFile,String targetFile) throws Exception {
// 第一步:获取通道
FileInputStream fin = new FileInputStream(sourceFile); //输入
FileOutputStream fou = new FileOutputStream(targetFile); //输出
FileChannel fc = fin.getChannel();
FileChannel fo = fou.getChannel();
// 第二步:创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
buffer.clear();
int r = fc.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fo.write(buffer);
}
}
public static void main(String[] args) throws Exception {
CopyFile test = new CopyFile();
test.readerFile("D:/Test/TypesInByteBuffer.java","D:/Test.txt");
}
}
java nio 实现的文件复制
最新推荐文章于 2023-06-11 08:50:19 发布