@Override public void run() { log.debug("Shutting down, deleting: "+deletions); try { synchronized (deletions) { List<String> pathsToDelete = new ArrayList<String>(deletions.keySet()); Collections.sort(pathsToDelete, Strings.lengthComparator().reverse()); for (String path: pathsToDelete) { try { deletions.remove(path).run(); } catch (Exception e) { log.warn("Unable to delete '"+path+"' on shutdown: "+e); log.debug("Trace for shutdown deletion problem: "+e, e); } } } } catch (Exception e) { log.warn("Unable to delete one or more paths ("+deletions+") on shutdown: "+e); log.debug("Trace for shutdown deletion problem: "+e, e); } } };
/** deletes the given file or directory and, in the case of directories, any contents; * similar to apache commons FileUtils.cleanDirectoryOnExit but corrects a bug in that implementation * which causes it to fail if content is added to that directory after the hook is registered */ public static void deleteOnExitRecursively(File directoryToCleanOrFile) { addShutdownFileDeletionHook(directoryToCleanOrFile.getAbsolutePath(), new FileDeletionHook(directoryToCleanOrFile, true)); }
/** deletes the given file or empty directory on exit * <p> * similar to {@link File#deleteOnExit()} except it is smart about trying to delete longer filenames first * (and the shutdown hook order does not use proprietary java hooks) * <p> * note this does not delete non-empty directories; see {@link #deleteOnExitRecursively(File)} for that */ public static void deleteOnExit(File directoryToDeleteIfEmptyOrFile) { addShutdownFileDeletionHook(directoryToDeleteIfEmptyOrFile.getAbsolutePath(), new FileDeletionHook(directoryToDeleteIfEmptyOrFile, false)); }