文件拷贝在Java编程中需要经常进行,各种拷贝方式有自身的特点和弊端,本文总结了常用的4中Java文件拷贝方法,为方便读者理解,均给出实际的源码,读者可以根据自己的项目特点选择合适的文件拷贝方法。
方法一:文件流-文件流传输
/**
* 文件拷贝
* @param f1 源文件
* @param f2 目标文件
* @return
* @throws Exception
*/
public static long copyFile(File f1, File f2) throws Exception {
long time = new Date().getTime();
int length = 2097152;
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
byte[] buffer = new byte[length];
while (true) {
int ins = in.read(buffer);
if (ins == -1) {
in.close();
out.flush();
out.close();
return new Date().getTime() - time;
} else
out.write(buffer, 0, ins);
}
}
实现方法很简单,分别对2个文件构建输入输出流,并且使用一个字节数组作为我们内存的缓存器, 然后使用流从f1 中读出数据到缓存里,在将缓存数据写到f2里面去.这里的缓存是2MB的字节数组
方法二:使用NIO中的管道-管道传输
/**
* 使用NIO进行文件拷贝
* @param f1 源文件
* @param f2 目标文件
* @return
* @throws Exception
*/
public static long copyFileNIO(File f1, File f2) throws Exception {
long time = new Date().getTime();
int length = 2097152;
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
FileChannel inC = in.getChannel();
FileChannel outC = out.getChannel();
int i = 0;
while (true) {
if (inC.position() == inC.size()) {
inC.close();
outC.close();
return new Date().getTime() - time;
}
if ((inC.size() - inC.position()) < 20971520)
length = (int) (inC.size() - inC.position());
else
length = 20971520;
inC.transferTo(inC.position(), length, outC);
inC.position(inC.position() + length);
i++;
}
}
实现方法:在第一种实现方法基础上对输入输出流获得其管道,然后分批次的从f1的管道中向f2的管道中输入数据每次输入的数据最大为2MB
<12>
【发表评论0条 】