多线程复制文件Java_Java多线程复制文件操作

//复制文件方法,采用的是FileChannel,效率更高一些

public static void copyFile(File from, File to, Thread t){

FileInputStream fis = null;

FileOutputStream fos = null;

FileChannel in = null;

FileChannel out = null;

try {

System.out.println("线程:" + t.getName() + "正在复制" + from.getName() + "...");

fis = new FileInputStream(from);

fos = new FileOutputStream(to);

in = fis.getChannel();

out = fos.getChannel();

in.transferTo(0, in.size(), out);

System.out.println("文件" + from.getName() + "复制结束");

} catch (IOException e) {

System.out.println("IO异常:" + e);

} finally{

try {

if(fis != null){

fis.close();

}

if(fos != null){

fos.close();

}

if(in != null){

in.close();

}

if(out != null){

out.close();

}

} catch (IOException e) {

System.out.println("关闭流异常:" + e);

}

}

}

//利用线程池,拿出4个线程

ExecutorService executorService = Executors.newFixedThreadPool(4);

//这个是可以定时执行的

//ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);

//注意需要事先构造一个二维数组

for (int i = 0; i < files.length; i++) {

String[] file = files[i];

File from = null;

File to = null;

for (int j = 0; j < file.length; j++) {

from = new File(file[0]);

to = new File(file[1]);

}

final File from_tmp = from;

final File to_tmp = to;

executorService.execute(new Runnable() {

@Override

public void run() {

CopyFileUtils.copyFile(from_tmp, to_tmp, Thread.currentThread());

}

});

}

executorService.shutdown();//执行完关闭

//定时的写法如下

for (int i = 0; i < files.length; i++) {

String[] file = files[i];

File from = null;

File to = null;

for (int j = 0; j < file.length; j++) {

from = new File(file[0]);

to = new File(file[1]);

}

final File from_tmp = from;

final File to_tmp = to;

scheduledExecutorService.schedule(new Runnable() {

@Override

public void run() {

CopyFileUtils.copyFile(from_tmp, to_tmp, Thread.currentThread());

}

}, 5, TimeUnit.SECONDS);//延迟5秒钟执行

}

scheduledExecutorService.shutdown();//执行完毕后关闭

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值