There is a directory structure, from which I need to list all the folders, which contains at least one file. So when a folder contains just subfolders, it shouldn't be listed. I tried to use following code for this, but empty folders are present in output.
Files.walk(Paths.get("C://testfolderstruct")).filter(Files::isDirectory).filter(Files::exists).forEach(System.out::println);
Folder structure:
C:.
└───T1
├───T2
└───T3
test.txt
Expected output:
C:\_privat\teszt\T1\T3
Files.exists() does only check if the given path does exist but not if it contains files. You have to get a list of files in your path. Try something like this:
public static void main(String[] args) throws IOException {
Files.walk(Paths.get("C://testfolderstruct"))
.filter(Files::isDirectory)
.filter(p -> checkIfEmpty(p))
.forEach(System.out::println);
}
private static boolean checkIfEmpty(Path directory) {
try {
return Files.list(directory)
.filter(p -> !Files.isDirectory(p))
.findAny()
.isPresent();
}
catch (IOException e) {
return false;
}
}