1

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 .

shmosel
  • 49,289
  • 6
  • 73
  • 138
baum
  • 87
  • 2
  • 7
  • 1
    Did you try [this](https://stackoverflow.com/a/57007478/1553851)? – shmosel Jun 23 '21 at 18:18
  • No - but that does the job! Thanks for make anightmerica green again;-) – baum Jun 23 '21 at 18:54
  • 1
    You have a stream of `Path` and convert it to the legacy `File`, to get exactly the problems of the legacy API you asked for. Use `Files.delete(Path)` and catch the exception, then let the exception tell you why the file has not been deleted. – Holger Jun 24 '21 at 10:47

0 Answers0