I am creating comfort methods to delete files and dirs. One of should delete all sub dirs and all files in a dir without deleting the dir itself.
In the unit test I create a structure like this
./SubDir2
./SubDir2/SubDir2SubDir1 fileToDeleteOnSubDir2SubDir1.txt
./SubDir2/SubDir2SubDir2 (contains no file)
So passing SubDir2 should delete both dirs and the file in them.
First I tried:
public static void deleteFilesAndSubDirsInDirectory(Path directory) throws TestException {
try {
Files.walk(directory)
.map(Path::toFile)
.forEach(File::delete);
} catch (IOException e) {
throw new TestException("Could not delete all files and subdirectories in dir "
+ directory.getFileName()
+ ": " + e.getMessage());
}
}
When I pass subDir2, this deletes the file and SubDir2SubDir2. But not SubDir2SubDir1. Why? Path can be both file and directory??
Then I checked stackoverflow as usual found in Delete all files in directory (but not directory) - one liner solution
Arrays.stream(directory.toFile().listFiles()).forEach(File::delete);
which looked promising. But the result was worse:
When I pass subDir2 this deletes only SubDir2SubDir2.
SubDir2SubDir1 and its file remain.
I would like to understand better what's going wrong in these streams. I wonder how to better test and debug streams as this is a kind of a black box thing leading to a lot of tries and errors.
Before I go back to plain old java it would be great if anybody would have a suggestion how to implement this method correclty using streams .