Java FileCleaner-class And Method Code Example


Here's an example of how to use the FileCleaner class from the org.apache.commons.io package in Java to schedule the deletion of a file when the JVM exits:

import org.apache.commons.io.FileCleaner;
import java.io.File;

public class Main {
    public static void main(String[] args) {
        File file = new File("path/to/file");
        FileCleaner.track(file, new FileCleaner.Trackable() {
            public void delete() {
                file.delete();
            }
            public boolean isDeleted() {
                return file.exists();
            }
        });
    }
}

This example shows how to use the track() method from the FileCleaner class to schedule the deletion of a file when the JVM exits. The FileCleaner.Trackable interface is implemented to define the delete() and isDeleted() methods that will be called when the JVM exits.

It's important to note that FileCleaner is deprecated as of commons-io 2.6, and it was removed in version 2.8 , you can use File.deleteOnExit() instead which is part of the JDK.