java中拷贝文件_java中的拷贝文件FileChannel

以前用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既快速,又省内存。

版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值