文章目录
- 一、记录文件相关操作方法
- 二、代码
- 1.读取路径返回List\<File>
- 2.读取路径返回List\<String>
- 3.删除文件夹
- 4.删除文件
一、记录文件相关操作方法
二、代码
1.读取路径返回List<File>
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;import java.io.File;
import java.util.ArrayList;
import java.util.List;
/*** 读取路径返回List<File>* @param directoryPath 路径* @return 结果*/public static List<File> listFilesReturnFileList(String directoryPath) {logger.info("-listFilesReturnFileList-directoryPath:{}", directoryPath);File directory = new File(directoryPath);List<File> fileList = new ArrayList<>();if (directory.exists() && directory.isDirectory()) {File[] files = directory.listFiles();if (files != null) {for (File file : files) {fileList.add(file);}}}return fileList;}
2.读取路径返回List<String>
/*** 读取路径返回List<String>* @param directoryPath 路径* @return 结果*/public static List<String> listFilesReturnFileNameList(String directoryPath) {logger.info("-listFilesReturnFileNameList-directoryPath:{}", directoryPath);File directory = new File(directoryPath);List<String> fileList = new ArrayList<>();if (directory.exists() && directory.isDirectory()) {File[] files = directory.listFiles();if (files != null) {for (File file : files) {fileList.add(file.getName());}}}return fileList;}
3.删除文件夹
* 删除文件夹* @param directoryPath 路径* @return 结果*/public static boolean deleteDirectory(String directoryPath) {logger.info("-deleteDirectory-directoryPath:{}", directoryPath);File directory = new File(directoryPath);if (!directory.exists()) {logger.info("Folder does not exist");return true; // 文件夹不存在,无需删除}if (!directory.isDirectory()) {logger.info("Not a Directory");return false; // 不是一个有效的文件夹路径}// 递归删除文件夹及其内容return deleteDirectoryRecursive(directory);}/*** 递归删除文件夹及其内容* @param directory 要删除的文件夹* @return 结果*/private static boolean deleteDirectoryRecursive(File directory) {logger.info("-deleteDirectoryRecursive-directory:{}", directory.getName());File[] files = directory.listFiles();if (files != null) {for (File file : files) {if (file.isDirectory()) {deleteDirectoryRecursive(file); // 递归删除子文件夹} else {file.delete(); // 删除文件}}}return directory.delete(); // 删除空文件夹}
4.删除文件
/*** 删除文件* @param filePath 路径* @return 结果*/public static boolean deleteFile(String filePath) {logger.info("-deleteFile-filePath:{}", filePath);File file = new File(filePath);if (!file.exists()) {logger.info("Folder does not exist");return true; // 文件不存在,无需删除}if (!file.isFile()) {logger.info("Not a File");return false; // 不是一个有效的文件路径}return file.delete(); // 删除文件}