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 实现的文件复制
最新推荐文章于 2021-10-28 17:44:59 发布
本文介绍了一个使用Java NIO进行文件复制的例子。通过创建FileInputStream和FileOutputStream的通道(FileChannel),并在ByteBuffer中读写数据来实现文件的快速复制。
1700

被折叠的 条评论
为什么被折叠?



