del file tree On Exit - Java java.nio.file

Java examples for java.nio.file:Path

Description

del file tree On Exit

Demo Code


import java.io.*;
import java.net.*;
import java.util.*;
import java.util.zip.*;
import org.apache.log4j.*;

public class Main{
    public static void deltreeOnExit(final File file) throws IOException {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override/*  ww  w  .j a  v  a 2s .co  m*/
            public void run() {
                try {
                    deltree(file);
                } catch (Exception ex) {
                }
            }
        });
    }
    public static void deltree(File file) throws IOException {
        //logger.info("file = " + file);
        if (!file.exists())
            return;
        if (file.isDirectory()) {
            String[] children = file.list();
            for (int i = 0; i < children.length; i++)
                deltree(new File(file, children[i]));
            file.delete();
        } else if (file.isFile())
            file.delete();
    }
}

Related Tutorials