第一阶段模块四作业第三题

题目:
使用线程池将一个目录中的所有内容拷贝到另外一个目录中,包含子目录中的内容。

思路:
线程池按照固定写法直接写就行,拷贝文件思路为调用递归,先列出目录下所有文件信息,如果是文件则拷贝,如果是文件夹,则递归。具体代码如下。

视频:https://www.bilibili.com/video/BV1nN411Q7Ld/

拷贝线程:

package step1_task4_homework.threadPollCopy;


import java.io.*;

public class FileCopyThread implements Runnable{
    @Override
    public void run() {
        try {
            fileCopy("D:/tmp/1","D:/tmp/2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param orgPath 原始文件夹
     * @param toPath  目标文件夹
     * @throws IOException
     */
    public void fileCopy(String orgPath,String toPath) throws IOException {
        File orgFile = new File(orgPath);
//        判断文件夹是否存在
        if (orgFile.exists()){
//            如果存在,列出该文件夹下的目录信息
            File[] files = orgFile.listFiles();
            byte[] bArr = new byte[1024];
//            for each遍历文件夹下的文件
            for (File f:files){
//               如果是文件
                if (f.isFile()){
                    int res = 0;
//                   定义缓存输入流和输出流
                    BufferedInputStream bis = new BufferedInputStream(
                            new FileInputStream(f.getAbsoluteFile()));
                    BufferedOutputStream bof = new BufferedOutputStream(
                            new FileOutputStream(toPath +"/"+ f.getName()));
//                  拷贝单个文件
                    while ((res = bis.read(bArr))!= -1){
                        bof.write(bArr,0,res);
                    }
//                  关闭流
                    bof.close();
                    bis.close();
                    System.out.println("文件复制中,从:" + f.getAbsolutePath() + "-->到:" + toPath +"/"+ f.getName());
                }
//              如果是文件夹,则执行递归
                if (f.isDirectory()){
//                  在目标文件夹下新建文件夹
                    File f1 = new File(toPath +"/"+ f.getName());
                    f1.mkdir();
                    fileCopy(f.getAbsolutePath(),toPath +"/"+ f.getName());
                }
            }

        }else {
            System.out.println("未找到待拷贝目录,请输入正确目录");
        }
    }
}

线程池:

package step1_task4_homework.threadPollCopy;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolCopyTest {
    public static void main(String[] args) {
//        创建有5个线程的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
//        布置任务
        executorService.execute(new FileCopyThread());
//        关闭线程池
        executorService.shutdown();
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值