How do I check if a path is a directory using Okio?

506 Views Asked by At

I am using Okio in Kotlin/Native. How do I check if a path (for example /path/to/directory) denotes a directory?

The scope of the check has to involve using the file system to check if the path denotes a file or a directory.

Example:

"/path/to/directory".toPath().isDirectory // should be true if it exists as a directory
"/path/to/file.txt".toPath().isDirectory // should be false if it does not exist or exists but is a file
1

There are 1 best solutions below

1
xdevs23 On BEST ANSWER

Here are two extension functions. They use FileSystem.metadataOrNull to retrieve metadata about the path and then proceed with checking if the path is a directory/regular file. In case the file does not exist or there is an error, false will be returned.

val fs = FileSystem.SYSTEM

val Path.isDirectory get() = fs.metadataOrNull(this)?.isDirectory == true
val Path.isRegularFile get() = fs.metadataOrNull(this)?.isRegularFile == true