visitFileTree

fun Path.visitFileTree(visitor: FileVisitor<Path>, maxDepth: Int = Int.MAX_VALUE, followLinks: Boolean = false)(source)

Visits this directory and all its contents with the specified visitor.

The traversal is in depth-first order and starts at this directory. The specified visitor is invoked on each entry encountered.

Example:

val cleanVisitor = fileVisitor {
onPreVisitDirectory { directory, _ ->
if (directory.name == "build") {
directory.deleteRecursively()
FileVisitResult.SKIP_SUBTREE
} else {
FileVisitResult.CONTINUE
}
}

onVisitFile { file, _ ->
if (file.extension == "class") {
file.deleteExisting()
}
FileVisitResult.CONTINUE
}
}

projectDirectory.visitFileTree(cleanVisitor)

Since Kotlin

2.1

Parameters

visitor

the FileVisitor that receives callbacks.

maxDepth

the maximum depth to traverse. By default, there is no limit.

followLinks

specifies whether to follow symbolic links, false by default. If true, the traversal follows symbolic links and visits the contents of the directories they point to.

See also

Throws

if a security manager is installed and it denies access to an entry reached during traversal.

if a visitor function throws an I/O exception.


fun Path.visitFileTree(maxDepth: Int = Int.MAX_VALUE, followLinks: Boolean = false, builderAction: FileVisitorBuilder.() -> Unit)(source)

Visits this directory and all its contents with the FileVisitor defined in builderAction.

This function works the same as Path.visitFileTree. It is introduced to streamline the cases when a FileVisitor is created only to be immediately used for a file tree traversal. The trailing lambda builderAction is passed to fileVisitor to get the file visitor.

Example:

projectDirectory.visitFileTree {
onPreVisitDirectory { directory, _ ->
if (directory.name == "build") {
directory.deleteRecursively()
FileVisitResult.SKIP_SUBTREE
} else {
FileVisitResult.CONTINUE
}
}

onVisitFile { file, _ ->
if (file.extension == "class") {
file.deleteExisting()
}
FileVisitResult.CONTINUE
}
}

Since Kotlin

2.1

Parameters

maxDepth

the maximum depth to traverse. By default, there is no limit.

followLinks

specifies whether to follow symbolic links, false by default. If true, the traversal follows symbolic links and visits the contents of the directories they point to.

builderAction

the function that defines the callbacks for handling entry visit events.

See also

Throws

if a security manager is installed and it denies access to an entry reached during traversal.

if a visitor function throws an I/O exception.

if the provided builderAction defines a FileVisitor incorrectly. See fileVisitor for details.