package com.xx.FileChannel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
/**
* @author 作者 E-mail:
* @version 创建时间:2012-9-20 上午10:49:50
* 类说明
*/
public class FileCopy {
public static void main(String[] args) throws IOException,
InterruptedException {
RandomAccessFile In = new RandomAccessFile("c:/aa.exe", "rw");
FileChannel fileIn = In.getChannel();
// FileChannel fileIn = new FileInputStream("c:/aa.exe").getChannel();
FileChannel fileOut = new FileOutputStream("c:/bb.exe").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
FileLock lock = fileIn.tryLock();
if (lock == null) {
System.out.println("文件正在使用....");
return;
}
while ((fileIn.read(buffer)) != -1) {
buffer.flip();// 重组缓冲区--->>>数据并没有改变,只改变索引键值
fileOut.write(buffer);// 写入通道中
buffer.clear();// 清楚缓冲区,已被下次使用
System.out.println("读写数据.....");
Thread.currentThread().sleep(500);
}
// fileIn.transferTo(0, fileIn.size(), fileOut);速度快
lock.release();
fileIn.close();
fileOut.close();
System.out.println("数据读写完成.....");
}
}
java简单实现复制文件
最新推荐文章于 2023-03-26 22:32:34 发布