Java Delete File on Exit deleteOnExit(File dir)

Here you can find the source of deleteOnExit(File dir)

Description

delete On Exit

License

Open Source License

Declaration

public static void deleteOnExit(File dir) 

Method Source Code


//package com.java2s;
import java.io.File;

import java.util.ArrayList;
import java.util.Collection;

public class Main {
    static final Collection<File> temporary = new ArrayList<File>();

    public static void deleteOnExit(File dir) {
        synchronized (temporary) {
            if (temporary.isEmpty()) {
                Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                    public void run() {
                        synchronized (temporary) {
                            for (File dir : temporary) {
                                deleteFileOrDir(dir, 256);
                            }//ww  w.  ja  v  a  2s.c o m
                        }
                    }
                }, "Temporary Directory Cleanup"));
            }
            temporary.add(dir);
        }
    }

    static void deleteFileOrDir(File dir, int max) {
        File[] listFiles = dir.listFiles();
        if (listFiles != null && max > 0) {
            for (File file : listFiles) {
                deleteFileOrDir(file, max - 1);
            }
        }
        dir.delete();
    }
}

Related

  1. deleteOnExit(File file)
  2. deleteOnExit(File file)
  3. deleteOnExit(final File file)
  4. deleteOnExit(final File file)