Java Recursively Delete a Directory

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Internal

Overview

Files.walk(configFrameworkRoot.toPath())
         .sorted(Comparator.reverseOrder())
         .map(Path::toFile)
         .forEach(File::delete);

Remove a Directory in a Junit Test

private Path testDirectory;

@Before
public void setUp() throws Exception {

   testDirectory = Files.createTempDirectory("test");
}

@After
public void cleanup() throws Exception {

  if (testDirectory != null) {

     Files.walk(testDirectory)
          .sorted(Comparator.reverseOrder())
          .map(Path::toFile)
          .forEach(File::delete);

     assertFalse(Files.exists(testDirectory));
     testDirectory = null;
  }
}