SpringBoot custom tool class—complete file cleaning function based on timer

Just copy and paste! !

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.chrono.ChronoLocalDate;
import java.time.format.DateTimeFormatter;

@Component // 表示将该类声明为一个组件,以便能够被Spring容器管理。
public class FileCleanupTask {

    //@Scheduled(cron = "0 0 0 */3 * ?") // 每隔三天凌晨12点触发任务
    //@Scheduled(cron = "0 */1 * * * ?") // 每隔一分钟触发任务
    @Scheduled(cron = "0 */2 * * * *") // 每隔2秒触发任务
    public void cleanupFiles() {
        String directoryPath = "/manage/uploadFile"; // 修改为你的上传文件存放的目录路径
        File directory = new File(directoryPath);

        // 检查目录是否存在
        // LocalDateTime twoMinutesAgo就代表了当前时间减去1分钟之后的时间点。这个时间点用于比较文件的创建时间,如果文件的创建时间早于twoMinutesAgo,则会被删除。
        if (directory.exists() && directory.isDirectory()) {
            //LocalDate threeDaysAgo = LocalDate.now().minusDays(3);
            // LocalDateTime.now():获取当前的日期和时间。.minusMinutes(1):通过调用minusMinutes方法,在当前时间基础上减去1分钟。
            LocalDateTime twoMinutesAgo = LocalDateTime.now().minusMinutes(1);
            deleteOlderFiles(directory, twoMinutesAgo);
        }
    }

    private void deleteOlderDirectories(File directory, LocalDate threeDaysAgo) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 获取文件夹的名称,格式为"yyyy-MM-ddXXX",其中XXX为随机数
                    String folderName = file.getName();
                    String dateString = folderName.substring(0, 10);
                    LocalDate folderDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

                    // 如果文件夹日期早于三天前的日期,则删除文件夹及其内容
                    if (folderDate.isBefore(threeDaysAgo)) {
                        deleteDirectory(file);
                        System.out.println("Deleted directory: " + file.getAbsolutePath());
                    }
                }
            }
        }
    }


    private void deleteOlderFiles(File directory, LocalDateTime twoMinutesAgo) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 获取文件夹的名称,格式为"yyyy-MM-ddXXX",其中XXX为随机数
                    String folderName = file.getName();
                    String dateString = folderName.substring(0, 10);
                    LocalDate folderDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    // 如果文件的创建时间早于两分钟前,则删除文件
                    if (folderDate.isBefore(ChronoLocalDate.from(twoMinutesAgo))) {
                        deleteDirectory(file);
                        System.out.println("Deleted file: " + file.getAbsolutePath());
                    }
                }
            }
        }
    }

    private LocalDateTime getCreationDateTime(File file) {
        long fileTimestamp = file.lastModified();
        return LocalDateTime.ofEpochSecond(fileTimestamp / 1000, 0, ZoneOffset.UTC);
    }

    private void deleteDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    file.delete();
                }
            }
        }
        directory.delete();
    }
}

illustrate: 

① Don’t write cron expressions yourself, use the online Cron expression generator (pppet.net)

②. Remember to add @EnableScheduling to the startup class // Enable scheduled tasks and regularly delete files on the server

③. Pay attention to the type of folder to be deleted (the folder name consists of a date and a three-digit random number, and it cannot be deleted if it does not contain the date)

④, the understanding of the file path

import java.io.File;

public class DirectoryExistsTest {
    public static void main(String[] args) {
        String directoryPath = "/manage/uploadFile"; // 相对路径
        File directory = new File(directoryPath);

        // 判断目录是否存在
        if (directory.exists() && directory.isDirectory()) {
            System.out.println("目录 " + directory.getAbsolutePath() + " 存在。");
        } else {
            System.out.println("目录 " + directory.getAbsolutePath() + " 不存在或不是一个目录。");
        }
    }
}

         Through this test class, we can find that String directoryPath = "manage/uploadFile"; the generated directory E:\excelreport\manage\uploadFile does not exist or is not a directory, but the directory E:\manage\uploadFile exists.

        In fact, manage/uploadFileit is a relative path, which is relative to the current working directory. When a Java program is executed, there will be a current working directory, which depends on where you run the program. For example, if your Java program files are located E:\excelreportunder the folder, the current working directory will be E:\excelreport.

Instead, /manage/uploadFileis an absolute path, which represents the complete path starting from the root directory of the system. In Windows systems, the root directory is usually the root directory of the hard disk, such as C:\or D:\, while in Linux systems, the root directory is represented as /.

So, when using a relative path, it concatenates the current working directory with the relative path to form a full path; when using an absolute path, it represents the full path starting from the root directory.

⑤. Understanding whether directory.exists() && directory.isDirectory()   exists in the file directory 

  directory.exists()Method is used to determine whether the specified directory exists. Click on the source code of the directory.exists() method to see:

        First, System.getSecurityManager()get SecurityManagerthe object by method, and if there is a security manager, call to security.checkRead(path)check if you have permission to read the directory.

        Next, isInvalid()a method is called to check whether the current Fileobject is invalid (for example, due to an empty pathname, etc.). If it is invalid, it returns directly falseto indicate that the directory does not exist.

        Then, fs.getBooleanAttributes(this)get the filesystem properties of the specified directory by calling the method, where fsis FileSystemthe object. The obtained attribute value can be judged by bitmask.

FileSystem.BA_EXISTSFinally, perform a bitwise AND operation on         the obtained attribute values . If the result is not 0, it means that the directory exists and returns true; otherwise, it means that the directory does not exist and returns false. In summary, directory.exists()the method determines whether the specified directory exists by checking the validity of the path and obtaining the file system attributes.

同理,isDirectory()Method used to determine Filewhether the current object represents a directory. The method is implemented as follows:

        First, System.getSecurityManager()get SecurityManagerthe object by method, and if there is a security manager, call to security.checkRead(path)check if you have permission to read the directory.

        Next, isInvalid()a method is called to check whether the current Fileobject is invalid (e.g. due to an empty pathname, etc.). If it is invalid, it will be returned directly falseto indicate that it is not a directory.

        Then, fs.getBooleanAttributes(this)get Filethe file system properties of the current object by calling the method, where fsis FileSystemobject. The obtained attribute value can be judged by bitmask.

FileSystem.BA_DIRECTORYFinally, perform a bitwise AND operation on the         obtained attribute values . If the result is not 0, it means it is a directory and returns true; otherwise, it means it is not a directory and returns false. To sum up, the method determines whether the current object represents a directory isDirectory()by checking the validity of the path and obtaining the file system attributes .File

⑤. Understanding of the method of deleting files (folders):

private void deleteDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    file.delete();
                }
            }
        }
        directory.delete();
    }

         This code uses Fileclasses and recursive methods in Java to delete all files and subdirectories in the specified directory.

/manage/uploadFileFirst, create an object representation directory         using an absolute path File. Then use directory.exists()the and directory.isDirectory()method to determine whether the directory exists and is a directory.

        Next, use directory.listFiles()the method to get all files and subdirectories in the directory and return an Filearray. If the array is not empty, use a loop to iterate through each element in the array.

        For each element, first determine whether it is a directory. If it is a directory, call deleteDirectory()the method recursively and pass in the current directory as a parameter to implement a depth-first deletion operation, that is, delete the content in the subdirectory first.

        If the element is not a directory but a file, file.delete()the method is called to delete the file.

        After completing the deletion of each file and subdirectory, finally call directory.delete()the method to delete the current directory itself.

        Recursively delete all files and folders in a directory and its subdirectories, making sure to delete the contents of the subdirectory before deleting the parent directory. Eventually, the entire directory structure is completely deleted.

running result:

In the window environment

Linux environment

​​​​​​​

Guess you like

Origin blog.csdn.net/weixin_49171365/article/details/132338209