题目:
使用线程池将一个目录中的所有内容拷贝到另外一个目录中,包含子目录中的内容。
思路:
线程池按照固定写法直接写就行,拷贝文件思路为调用递归,先列出目录下所有文件信息,如果是文件则拷贝,如果是文件夹,则递归。具体代码如下。
视频: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();
}
}