Java文件夹复制
package lab.lab2;
/**
* @Title: CopyDir
* @Description:复制一个文件夹的内容到另一个文件夹
* @Auther: zzp
* @Version: 1.0
* @create 2020/4/17 15:24
*/
import java.io.*;
public class CopyDir {
public static void copyDirectory(String oldPath, String newPath) throws IOException {
String[] filePath = (new File(oldPath)).list(); //文件夹内文件的名字数组
int newPathExist = 1;//记录初始状态下文件夹是否存在,存在为1,不存在为0
if (!(new File(newPath)).exists()) { //判断要目标文件夹是否存在不存在则创建,并将newPathExist置0
(new File(newPath)).mkdir();
newPathExist = 0;
}
if(newPathExist ==1){
String[] filePath2 = (new File(newPath)).list();
for (int i = 0; i < filePath.length; i++) {
int k =0;//文件是否已在目标文件夹中存在 存在为1,不存在为0
for(int j=0;j<filePath2.length;j++) {//新文件夹中是否存在相同的文件名 有则不复制
if(filePath2[j].equals(filePath[i])){
k=1;
}
}
if(k==0){
if ((new File(oldPath +"/" + filePath[i])).isDirectory()) { //判断是不是文件夹,是的话执行递归
copyDirectory(oldPath + "/" + filePath[i], newPath + "/" + filePath[i]);
} else if (new File(oldPath + "/" + filePath[i]).isFile()) {//判断是不是文件,是的话旧的文件拷至新的文件夹下
copyFile(oldPath + "/" + filePath[i], newPath + "/" + filePath[i]);
}
}
}
}else{
for (int i = 0; i < filePath.length; i++) {
if ((new File(oldPath + "/" + filePath[i])).isDirectory()) {
copyDirectory(oldPath + "/" + filePath[i], newPath + "/" + filePath[i]);
} else if (new File(oldPath + "/" + filePath[i]).isFile()) {
copyFile(oldPath + "/" + filePath[i], newPath + "/" + filePath[i]);
}
}
}
}
public static void copyFile(String oldPath, String newPath) throws IOException {//复制文件函数
FileInputStream fis = new FileInputStream(new File(oldPath));
FileOutputStream fos = new FileOutputStream(new File(newPath));
byte[] buf=new byte[2048];
int a = 0;
while((a = fis.read(buf)) != -1){
fos.write(buf, 0, a);
}
fis.close();
fos.close();
}
public static void main(String[] args) throws IOException {
copyDirectory("D:\\a", "D:\\b");
}
}