|
| 1 | +package net.lightbody.bmp.util; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | + |
| 6 | +import java.io.IOException; |
| 7 | +import java.nio.file.FileVisitResult; |
| 8 | +import java.nio.file.Files; |
| 9 | +import java.nio.file.Path; |
| 10 | +import java.nio.file.SimpleFileVisitor; |
| 11 | +import java.nio.file.attribute.BasicFileAttributes; |
| 12 | + |
| 13 | +/** |
| 14 | + * A Runnable that deletes the specified directory. Useful as a shutdown hook. |
| 15 | + */ |
| 16 | +public class DeleteDirectoryTask implements Runnable { |
| 17 | + // the static final logger is in this static inner class to allow the logger initialization code to use DeleteDirectoryTask |
| 18 | + // without prematurely initializing the logger when loading this class. since the 'log' field is in a static inner class, it will |
| 19 | + // only be initialized when it is actually used, instead of when the classloader loads the DeleteDirectoryTask class. |
| 20 | + private static class LogHolder { |
| 21 | + private static final Logger log = LoggerFactory.getLogger(DeleteDirectoryTask.class); |
| 22 | + } |
| 23 | + |
| 24 | + private final Path directory; |
| 25 | + |
| 26 | + public DeleteDirectoryTask(Path directory) { |
| 27 | + this.directory = directory; |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public void run() { |
| 32 | + try { |
| 33 | + Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { |
| 34 | + @Override |
| 35 | + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { |
| 36 | + try { |
| 37 | + Files.delete(file); |
| 38 | + } catch (IOException e) { |
| 39 | + LogHolder.log.warn("Unable to delete file or directory", e); |
| 40 | + } |
| 41 | + |
| 42 | + return FileVisitResult.CONTINUE; |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { |
| 47 | + try { |
| 48 | + Files.delete(dir); |
| 49 | + } catch (IOException e) { |
| 50 | + LogHolder.log.warn("Unable to delete file or directory", e); |
| 51 | + } |
| 52 | + |
| 53 | + return FileVisitResult.CONTINUE; |
| 54 | + } |
| 55 | + }); |
| 56 | + } catch (IOException e) { |
| 57 | + LogHolder.log.warn("Unable to delete file or directory", e); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments