Java Recursively Delete a Directory: Difference between revisions
Jump to navigation
Jump to search
(3 intermediate revisions by the same user not shown) | |||
Line 5: | Line 5: | ||
* [[Java#Subjects|Java]] | * [[Java#Subjects|Java]] | ||
* [[NIO 2 File API]] | * [[NIO 2 File API]] | ||
=Overview= | |||
<syntaxhighlight lang='java'> | |||
Files.walk(configFrameworkRoot.toPath()) | |||
.sorted(Comparator.reverseOrder()) | |||
.map(Path::toFile) | |||
.forEach(File::delete); | |||
</syntaxhighlight> | |||
<font color=darkgray>TODO: convert to Java.</font> | |||
<syntaxhighlight lang='groovy'> | |||
def static deleteDirectoryRecursively(def pipeline, String d) { | |||
File df = new File(d) | |||
String[] files = df.list() | |||
for(String s: files) { | |||
File f = new File(d, s) | |||
if (f.isDirectory()) { | |||
deleteDirectoryRecursively(pipeline, f.getPath()) | |||
} | |||
else { | |||
if (f.delete()) pipeline.print "deleted ${f}" | |||
} | |||
} | |||
if (df.delete()) pipeline.print "deleted ${df}" | |||
} | |||
</syntaxhighlight> | |||
=Remove a Directory in a Junit Test= | |||
<syntaxhighlight lang='java'> | |||
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; | |||
} | |||
} | |||
</syntaxhighlight> |
Latest revision as of 20:58, 5 April 2021
External
Internal
Overview
Files.walk(configFrameworkRoot.toPath())
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
TODO: convert to Java.
def static deleteDirectoryRecursively(def pipeline, String d) {
File df = new File(d)
String[] files = df.list()
for(String s: files) {
File f = new File(d, s)
if (f.isDirectory()) {
deleteDirectoryRecursively(pipeline, f.getPath())
}
else {
if (f.delete()) pipeline.print "deleted ${f}"
}
}
if (df.delete()) pipeline.print "deleted ${df}"
}
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;
}
}