package test;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Date;
/**
* 编写程序拷贝一个文件.
*
* @author Administrator
*
*/
public class Test_7_Copy {
public static long copyFile(File f1, File f2) throws Exception {
long time = new Date().getTime();
int length = 2097152;
if (!f1.exists()) {
System.out.println("源文件不存在");
} else if (f2 == null) {
System.out.println("文件名为null");
} else {
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
FileChannel inC = in.getChannel();
FileChannel outC = out.getChannel();
ByteBuffer b = null;
while (true) {
if (inC.position() == inC.size()) {
inC.close();
outC.close();
System.out.println("复制成功!");
return new Date().getTime() - time;
}
if ((inC.size() - inC.position()) < length) {
length = (int) (inC.size() - inC.position());
} else
length = 2097152;
b = ByteBuffer.allocateDirect(length);
inC.read(b);
b.flip();
outC.write(b);
outC.force(false);
}
}
return time;
}
}
java复制文件的一种方法
最新推荐文章于 2023-03-26 23:17:57 发布