import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* 用NIO流拷贝文件
* @author 万星明
* @version 1.0
* @time
*/
public class NIOCopy {
public static void main(String[] args) throws Exception {
//准备需要拷贝的文件与目标文件
File f1 = new File("");
File f2 = new File("h.mp4");
//创建输入流
FileInputStream fis = new FileInputStream(f1);
//根据读取流创建读取通道,同时将文件中的内容读入到通道中
FileChannel rChannel = fis.getChannel();
//创建输出流
FileOutputStream fos = new FileOutputStream(f2);
//根据输出流创建写入通道,将通道中的内容写入到文件中
FileChannel wChannel = fos.getChannel();
//创建缓冲区
ByteBuffer bBuffer = ByteBuffer.allocate((int)f1.length());
//将输入通道中的内容输入到缓冲区中
rChannel.read(bBuffer);
//将缓冲区的指针反转,指向起始位置
bBuffer.flip();
//将缓冲区的内容写入到输出通道
wChannel.write(bBuffer);
System.out.println("拷贝成功!");
//关流
fis.close();
fos.close();
}
}
java用NIO流拷贝文件
最新推荐文章于 2024-06-23 07:45:00 发布