package com.wujiahao.utils;
import org.springframework.context.annotation.Configuration;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
@Configuration
public class FileUtils {
/**
* 复制文件夹
* @param sourceDir 目标文件夹
* @param destDir 复制到的文件夹
* @throws IOException
*/
public static void copyDirectory(File sourceDir, File destDir) throws IOException {
if (!destDir.exists()) {
destDir.mkdirs();
}
// 获取源目录的名称,并在目标目录下创建同名目录
String sourceDirName = sourceDir.getName();
File destSubDir = new File(destDir, sourceDirName);
destSubDir.mkdirs();
for (File sourceFile : sourceDir.listFiles()) {
File destFile = new File(destSubDir, sourceFile.getName());
if (sourceFile.isDirectory()) {
copyDirectory(sourceFile, destSubDir);
} else {
Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
/**
* 删除文件
* @param filePath 文件路径
* @param filePath
*/
private static void deleteFile(String filePath) {
File file = new File(filePath);
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("文件删除成功:" + filePath);
} else {
System.out.println("文件删除失败:" + filePath);
}
} else {
System.out.println("文件不存在或不是一个文件:" + filePath);
}
}
/**
* 删除目录及其子目录下的所有文件
* @param dirPath 目标目录
*/
private static void deleteDirectory(String dirPath) {
File dir = new File(dirPath);
if (dir.exists() && dir.isDirectory()) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file.getAbsolutePath());
} else {
if (file.delete()) {
System.out.println("文件删除成功:" + file.getAbsolutePath());
} else {
System.out.println("文件删除失败:" + file.getAbsolutePath());
}
}
}
}
if (dir.delete()) {
System.out.println("目录删除成功:" + dirPath);
} else {
System.out.println("目录删除失败:" + dirPath);
}
} else {
System.out.println("目录不存在或不是一个目录:" + dirPath);
}
}
/**
* 创建目录
* @param dirPath
*/
private static void createDirectory(String dirPath) {
File dir = new File(dirPath);
if (!dir.exists()) {
if (dir.mkdir()) {
System.out.println("目录创建成功:" + dirPath);
} else {
System.out.println("目录创建失败:" + dirPath);
}
} else {
System.out.println("目录已经存在:" + dirPath);
}
}
/**
* 创建多级目录
* @param dirsPath
*/
private static void createDirectories(String dirsPath) {
File dirs = new File(dirsPath);
if (!dirs.exists()) {
if (dirs.mkdirs()) {
System.out.println("多层目录创建成功:" + dirsPath);
} else {
System.out.println("多层目录创建失败:" + dirsPath);
}
} else {
System.out.println("多层目录已经存在:" + dirsPath);
}
}
}
文件操作:复制、删除
于 2024-04-23 15:31:18 首次发布