Kotlin – Get File Name
To get the name of a file in Kotlin, you can use the File
class from the java.io
package. The File
class provides the name
property, which returns the name of the file or directory denoted by the path.
In this tutorial, we’ll learn how to get the name of the file from File object in Kotlin, with an example.
Steps to Get the File Name in Kotlin
To get the name of a file in Kotlin, follow these steps:
- Import the
File
class from thejava.io
package. - Create a
File
object using the file path. - Access the
name
property of theFile
object to get the file name.
Kotlin Example Program to Get File Name
Here’s an example program that demonstrates how to retrieve the name of a file named 'example.txt'
.
Main.kt
import java.io.File
fun main() {
val filePath = "path/to/your/file/example.txt" // Replace with your file path
val file = File(filePath)
val fileName = file.name
println("The file name is: $fileName")
}
Output
The file name is: example.txt
The output will display the name of the file.
Summary
In this Kotlin tutorial, we have learnt how to get the name of a file from given file path, using File.name property, with the help of an example program.