package com.zhgd.xmgl.util; import cn.hutool.json.JSONUtil; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @Slf4j public class Fileutils { public static void main(String[] args) { log.info(JSONUtil.toJsonStr(getFileNameList("D:/itbgpImage/", "2021-12-20 00:00:00", "2021-12-25 00:00:00"))); } public static List getFileNameList(String path, String statrTIme, String endTime) { List newfileList = new ArrayList<>(); List filesList = getFilesList(path, newfileList); List newfile = searchData(filesList, statrTIme, endTime); List fileNameList = new ArrayList<>(); if (newfile != null && newfile.size() > 0) { File root = new File(path); String rootPath = root.getAbsolutePath(); for (File file : newfile) { String filePath = file.getAbsolutePath().replace(rootPath, "").replace(file.getName(), "").replace("\\", "/"); if (filePath.length() > 0) { if (!filePath.endsWith("/")) { filePath = filePath + "/"; } if (filePath.startsWith("/")) { filePath = filePath.substring(1, filePath.length()); } } fileNameList.add(filePath + file.getName()); } } return fileNameList; } public static List getFilesList(String filePath, List fileList) { File root = new File(filePath); if (!root.exists()) { log.info(filePath + " not exist!"); } else { File[] files = root.listFiles(); for (File file : files) { if (file.isDirectory()) { getFilesList(file.getAbsolutePath(), fileList); } else { fileList.add(file); } } } return fileList; } //根据文件修改时间进行比较的内部类 static class CompratorByLastModified implements Comparator { @Override public int compare(File f1, File f2) { long diff = f1.lastModified() - f2.lastModified(); if (diff > 0) {// 倒序排列为-1 正序为1 return -1; } else if (diff == 0) { return 0; } else {// 倒序排列为1 正序为-1 return 1; } } } public static List searchData(final List fileArray, String startTime, String endTime) { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //开始时间 LocalDateTime stadt = LocalDateTime.parse(startTime, df); //截止时间 LocalDateTime enddt = LocalDateTime.parse(endTime, df); return fileArray.stream().filter(s -> new Date(s.lastModified()).toLocaleString() != null && new Date(s.lastModified()).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().isAfter(stadt) && new Date(s.lastModified()).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().isBefore(enddt)).collect(Collectors.toList()); } }