package com.koudaitiku.manager;
import java.io.*;
/**
* @program: kd-manager
* @author: Mr.ZPF
* @create: 2019-10-24 09:32
**/
public class CopyDirectory {
static String url1 = "H:\\1999年前后(都有)\\华东师范大学";
static String url2 = "H:\\1999年前后(都有)\\华东师范大学-cp\\1999年之前";
static String url3 = "H:\\1999年前后(都有)\\华东师范大学-cp\\1999年之后";
public static void main(String args[]) throws IOException {
// 创建目标文件夹
File targetFile2 = new File(url2);
if (!targetFile2.exists()) {
(new File(url2)).mkdirs();
}
File targetFile3 = new File(url3);
if (!targetFile3.exists()) {
(new File(url3)).mkdirs();
}
// 获取源文件夹当前下的文件或目录
File[] file = (new File(url1)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
String name = file[i].getName();
if (name.indexOf("19") != -1) {
System.out.println("共"+file.length+"个,这是第"+(i+1)+"个--------(文件夹)-------99年之前:" + file[i].getPath());
copyFile(file[i], new File(url2 + File.separator + file[i].getName()));
}else {
System.out.println("共"+file.length+"个,这是第"+(i+1)+"个--------(文件夹)-------99年之后:" + file[i].getPath());
copyFile(file[i], new File(url3 + File.separator + file[i].getName()));
}
// 复制文件
}
if (file[i].isDirectory()) {
// 复制目录
String sourceDir = url1 + File.separator + file[i].getName();
String targetDir2 = url2 + File.separator + file[i].getName();
String targetDir3 = url3 + File.separator + file[i].getName();
String name = file[i].getName();
if (name.indexOf("19") != -1) {
System.out.println("共"+file.length+"个,这是第"+(i+1)+"个-------(文件)--------99年之前:" + file[i].getPath());
copyDirectiory(sourceDir, targetDir2);
}else {
System.out.println("共"+file.length+"个,这是第"+(i+1)+"个-------(文件)--------99年之后:" + file[i].getPath());
copyDirectiory(sourceDir, targetDir3);
}
}
}
}
// 复制文件
public static void copyFile(File sourceFile, File targetFile)
throws IOException {
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
//关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
// 复制文件夹
public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException {
// 新建目标目录
(new File(targetDir)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile = file[i];
// 目标文件
File targetFile = new
File(new File(targetDir).getAbsolutePath()
+ File.separator + file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 准备复制的源文件夹
String dir1 = sourceDir + File.separator + file[i].getName();
// 准备复制的目标文件夹
String dir2 = targetDir + File.separator + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
}