一、记录文件相关操作方法
二、代码
1.读取路径返回List\
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
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\
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);
}
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.删除文件
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();
}