net.dankito.utils.filesystem.FileSystemWalker.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
The newest version!
package net.dankito.utils.filesystem
import org.slf4j.LoggerFactory
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.FileVisitor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
open class FileSystemWalker : IFileSystemWalker {
companion object {
private val log = LoggerFactory.getLogger(FileSystemWalker::class.java)
}
override fun listFiles(startDir: Path): List {
val discoveredFiles = mutableListOf()
walk(startDir) { discoveredFile: Path ->
discoveredFiles.add(discoveredFile)
}
return discoveredFiles
}
override fun listFilesAndFolders(startDir: Path): FileSystemWalkResult {
val discoveredFiles = mutableListOf()
val discoveredFolders = mutableListOf()
listAllFilesAndFoldersWalk(startDir, { discoveredFolders.add(it) }, { discoveredFiles.add(it) })
return FileSystemWalkResult(discoveredFiles, discoveredFolders)
}
override fun walk(startDir: Path, discoveredFileCallback: (Path) -> Unit) {
detailedWalk(startDir) { visitedFile: VisitedFile ->
visitedFile.path?.let { discoveredFile ->
discoveredFileCallback(discoveredFile)
FileVisitResult.CONTINUE
}
}
}
override fun listAllFilesAndFoldersWalk(startDir: Path, preVisitDirectory: ((directory: VisitedFile) -> Unit)?,
visitedFileCallback: (VisitedFile) -> Unit) {
detailedWalk(startDir, false, {
preVisitDirectory?.invoke(it)
null
}, null, {
visitedFileCallback.invoke(it)
null
})
}
override fun detailedWalk(startDir: Path, abortOnError: Boolean,
preVisitDirectory: ((directory: VisitedFile) -> FileVisitResult?)?,
postVisitDirectory: ((directory: VisitedFile) -> FileVisitResult?)?,
visitedFileCallback: (VisitedFile) -> FileVisitResult?) {
Files.walkFileTree(startDir, object : FileVisitor {
// files:
override fun visitFile(file: Path?, attributes: BasicFileAttributes?): FileVisitResult {
return visitedFileCallback(VisitedFile(file, attributes)) ?: FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path?, exception: IOException?): FileVisitResult {
log.error("Could not visit file '$file'", exception)
visitedFileCallback(VisitedFile(file, null, exception))
return if (abortOnError) FileVisitResult.TERMINATE else FileVisitResult.CONTINUE
}
// directories:
override fun preVisitDirectory(directory: Path?, attributes: BasicFileAttributes?): FileVisitResult {
return preVisitDirectory?.invoke(VisitedFile(directory, attributes))
?: FileVisitResult.CONTINUE
}
override fun postVisitDirectory(directory: Path?, exception: IOException?): FileVisitResult {
return postVisitDirectory?.invoke(VisitedFile(directory, null, exception))
?: FileVisitResult.CONTINUE
}
})
}
}