java代码复制文件夹以及文件以及删除文件夹
我们需要将template下的三个文件夹以及文件复制到demo文件夹下:
public class FileUtil {
/**
* 复制文件
* @param oldPath 旧路径
* @param newPath 新路径
*/
public static void copyFile(File oldPath, File newPath) {
try {
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(oldPath));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newPath))) {
int len; //读取文件的字节数
byte[] bys = new byte[1024];
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
}
} catch (IOException e) {
throw new RuntimeException("复制文件失败:" + e);
}
}
/**
* 复制文件夹
* @param oldPath 旧路径
* @param newPath 新路径
*/
public static void copyFolder(String oldPath, String newPath) {
File oldFile = new File(oldPath);
//获取该路径下所有的文件夹和文件
File[] files = oldFile.listFiles();
//遍历
for (File file : files) {
//生成新路径
String targetPath = newPath + File.separator + file.getName();
File targetFile = new File(targetPath);
if (!file.isDirectory()) {
//旧路径下的是一个文件, 则复制文件
copyFile(file, targetFile);
} else {
//是文件夹,则创建文件夹,再递归
targetFile.mkdirs();
//将两个文件夹路径传入
copyFolder(oldPath + File.separator + file.getName(), newPath + File.separator + file.getName());
}
}
}
/**
* 递归删除文件和文件夹
* @param file 文件路径
*/
public static void deleteFile(File file) {
if (file.exists()) {
if (file.isDirectory()) {
//是文件夹, 获取文件列表
File[] files = file.listFiles();
if (files.length > 0) {
//不是空文件夹,遍历,递归删除
for (File file1 : files) {
deleteFile(file1);
}
}
}
//统一执行删除
file.delete();
}
}
}