以前用Java拷贝文件,只知道写byte数组循环拷贝,今天知道了可以用FileChannel进行拷贝,上代码:
下边是传统的byte数组拷贝方法
private void copyFilefromByte() throws IOException {
long start = System.currentTimeMillis();
MemorySee memorySee = new MemorySee();
memorySee.begin();
File name = new File("D:\\a\\hehe.zip");
File n1 = new File("D:\\a\\a.zip");
FileInputStream fileInputStream = new FileInputStream(name);
n1.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(n1);
byte[] bytes = new byte[1024000];
int length = -1;
while ((length = fileInputStream.read(bytes, 0, bytes.length)) != -1) {
fileOutputStream.write(bytes, 0, length);
}
fileOutputStream.flush();
fileOutputStream.close();
fileInputStream.close();
memorySee.end();
memorySee.sayMemoryUse();
long end = System.currentTimeMillis();
System.out.println("run time:" + (end - start));
}
下边是使用FileChannel拷贝文件的方法:
private void copyFileFromCannel() throws IOException {
long start = System.currentTimeMillis();
MemorySee memorySee = new MemorySee();
memorySee.begin();
File name = new File("D:\\a\\hehe.zip");
File n1 = new File("D:\\a\\b.zip");
FileInputStream fileInputStream = new FileInputStream(name);
FileChannel fileChannel = fileInputStream.getChannel();
n1.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(n1);
FileChannel fileChannel2 = fileOutputStream.getChannel();
int position = -1;
long fileSize = name.length();
int writeLength = 0;
while (true) {
writeLength += fileChannel2.transferFrom(fileChannel, writeLength,
fileSize - writeLength);
System.out.println("writeLength:"+writeLength);
if (writeLength == fileSize) {
break;
}
}
fileChannel2.close();
fileChannel.close();
memorySee.end();
memorySee.sayMemoryUse();
long end = System.currentTimeMillis();
System.out.println("run time:" + (end - start));
}还有一个辅助打印memory的类:
class MemorySee{
private long startM =0;
private long endM =0;
public void begin(){
Runtime.getRuntime().gc();
startM=Runtime.getRuntime().freeMemory();
}
public void end(){
endM=Runtime.getRuntime().freeMemory();
}
public void sayMemoryUse(){
System.out.println(startM-endM);
}
}
最后输出结果:
使用FileChannel拷贝的时间,要比byte节约大约1/2时间,或者更多,内存占用总比byte少,如果要提高byte的时间,那么就要提高byte的大小,这样就会消耗更多内存,总之,使用FileChannel既快速,又省内存。
版权声明:本文为博主原创文章,未经博主允许不得转载。