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.

Download Code

 
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).

Download Code

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:

Download Code

 
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.

Download Code

That’s all about creating a directory in Kotlin.