In this tutorial, you shall learn how to create a directory in Kotlin, using File.mkdir() function, with example programs.
Kotlin Create a directory
To create a directory in Kotlin, we can use mkdir() function from the java.io.File class.
Steps to create a directory
- Consider that we are given a path to a directory.
- Create a File object with the given directory path
- Call mkdir() on the File object.
val directory = File("path/to/directory") directory.mkdir()
Examples 3
1 Create a new directory
In the following program, we create a directory named mydata
.
Main.kt
import java.io.File fun main() { val directory = File("mydata") directory.mkdir() println("Directory created successfully.") }
Output
Directory created successfully.
2 Directory already exists
From the above program, we have created a directory named mydata
.
Now, let us try to create a directory with the same name mydata
.
Main.kt
import java.io.File fun main() { val directory = File("mydata") directory.mkdir() println("Directory created successfully.") }
Output
Directory created successfully.
Even if the directory is already present, the output seems to be same in both the above cases.
3 Check if directory exists before creating
We can check if directory is already present using File.exists() method. We can use this as a condition to check if the directory already exists, and only create the directory if it does not exist.
The following is the modified program with an if-else statement to create a new directory only if the directory does not exist.
Main.kt
import java.io.File fun main() { val directory = File("mydata") if (!directory.exists()) { directory.mkdir() println("Directory created successfully.") } else { println("Directory already exists.") } }
Output
Directory already exists.
Conclusion
In this Kotlin Tutorial, we learned how to create a new directory using File.mkdir() function.