FileUtils { public static void deleteDirectoryRecursively(File file) { File[] contents = file.listFiles(); if (contents != null) { for (File f : contents) { deleteDirectoryRecursively(f); } } boolean deleted = file.delete(); if (deleted) { log.debug("File {} was deleted", file.getAbsolutePath()); } }  static void deleteDirectoryRecursively(File file);  }
@Test void shouldDeleteShallowDirectory() throws IOException { File parent = new File("parent"); parent.mkdir(); File test = new File("parent/test.txt"); test.createNewFile(); assertTrue(parent.isDirectory()); assertTrue(test.isFile()); FileUtils.deleteDirectoryRecursively(parent); assertFalse(parent.isDirectory()); assertFalse(test.isFile()); }
@Test void shouldDeleteSingleFile() throws IOException { File test = new File("test.txt"); test.createNewFile(); assertTrue(test.isFile()); FileUtils.deleteDirectoryRecursively(test); assertFalse(test.isFile()); }
@Test void shouldDeleteDeepDirectory() throws IOException { File parent = new File("parent/child/deep"); parent.mkdirs(); File test = new File("parent/child/deep/test.txt"); test.createNewFile(); File test2 = new File("parent/child/test2.txt"); test2.createNewFile(); File test3 = new File("parent/test3.txt"); test3.createNewFile(); assertTrue(parent.isDirectory()); assertTrue(test.isFile()); assertTrue(test2.isFile()); assertTrue(test3.isFile()); FileUtils.deleteDirectoryRecursively(new File("parent")); assertFalse(parent.isDirectory()); assertFalse(test.isFile()); assertFalse(test2.isFile()); assertFalse(test3.isFile()); }