Create a directory in Kotlin
This post will discuss how to create a directory in Kotlin, including any non-existent parent directories.
1. Using Files.createDirectories()
function
The standard solution to create a single directory in Kotlin is using the Files.createDirectory()
function. It throws FileAlreadyExistsException
if the specified directory already exists and IOException
if the parent directory is non-existent.
1 2 3 4 5 6 7 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val path = "/existingdir/dir" Files.createDirectory(Paths.get(path)) } |
To create any non-existent parent directories first before creating the main directory, consider using the Files.createDirectories()
function. Unlike the Files#createDirectory()
function, it does not throw an exception if the directory already exists. For instance, the following snippet creates the parent directory dir1
and subdirectory dir2
(if it doesn’t exist).
1 2 3 4 5 6 7 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val path = "/dir1/dir2" Files.createDirectories(Paths.get(path)) } |
2. Using File#mkdirs()
function
Alternately, we can use the Files#createDirectory()
function to create a new single directory. Unlike the previous approach, it doesn’t throw an exception but simply returns true
or false
value depending upon the directory is created or not. It can be used as follows:
1 2 3 4 5 6 7 8 |
import java.io.File fun main() { val directory = File("/existingdir/dir") if (directory.mkdir()) { println("Directory created successfully") } } |
To create a hierarchy of directories, use the File#mkdirs()
function instead. It creates the directory with the specified pathname, including any non-existent parent directories.
1 2 3 4 5 6 7 8 |
import java.io.File fun main() { val directory = File("/dir1/dir2") if (directory.mkdirs()) { println("Directory created successfully") } } |
That’s all about creating a directory in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)