FileSupport { public static boolean deleteHierarchyIfEmpty(File limit, File start) { return limit.isDirectory() && start.isDirectory() && (isEqual(limit, start) || (isParent(limit, start) && start.list().length == 0 && start.delete() && deleteHierarchyIfEmpty( limit, start.getParentFile()))); } private  FileSupport(); static File copy(File sourceLocation, File targetLocation); static File copy(File sourceFile, File targetFile, boolean overwrite); static File link(File sourceLocation, File targetLocation); static File link(final File sourceLocation, final File targetLocation, final boolean overwrite); static boolean supportsLinking(File sourceLocation, File targetLocation); static boolean deleteHierarchyIfEmpty(File limit, File start); static boolean isEqual(File a, File b); static boolean isParent(File a, File b); static boolean delete(File f); static boolean deleteQuietly(File f); static boolean deleteQuietly(File f, boolean recurse); static boolean delete(File f, boolean recurse); static boolean delete(File dir, int mode); static void setTempDirectory(File tmpDir); static File getTempDirectory(); static File getTempDirectory(String subdir); static final int DELETE_FILES; static final int DELETE_ROOT; }
@Test public void testDeleteHierarchyIfEmpty() throws Exception { final File a = testFolder.newFile("test.tmp"); a.deleteOnExit(); final File tmpDir = a.getParentFile(); assertFalse(deleteHierarchyIfEmpty(tmpDir, a)); assertFalse(deleteHierarchyIfEmpty(a, a)); final File subDir1 = createDirWithRandomNameIn(tmpDir); final File subDir2 = createDirWithRandomNameIn(subDir1); final File subDir3 = createDirWithRandomNameIn(subDir2); final File subDir1File = createFileWithRandomNameIn(subDir1); final File subDir3File = createFileWithRandomNameIn(subDir3); assertFalse("file in sub dir 3 prevents deletion", deleteHierarchyIfEmpty(subDir1, subDir3)); assertTrue(subDir3.exists()); assertTrue(subDir3File.exists()); assertTrue(subDir3File.delete()); assertTrue("sub dir 3 and sub dir 2 are empty", deleteHierarchyIfEmpty(subDir1, subDir3)); assertFalse(subDir3.exists()); assertFalse(subDir2.exists()); assertTrue("sub dir 1 has not been deleted", subDir1.exists()); assertTrue(subDir2.mkdirs()); assertTrue(subDir3.mkdirs()); assertTrue(subDir1File.delete()); assertTrue("all sub dirs are empty", deleteHierarchyIfEmpty(tmpDir, subDir3)); assertFalse(subDir3.exists()); assertFalse(subDir2.exists()); assertFalse(subDir1.exists()); assertTrue(tmpDir.exists()); }