In this tutorial, you shall learn how to get the name of a file identified by a given path in Kotlin using File.name property, with example programs.
Kotlin – Get file name
To get the name of a file in Kotlin, you can use the name property of java.io.File class.
Step to get file name
- Consider that we have a file identified by a given path.
- Create a file object with the given path using java.io.File class, and read the name of the file object using File.name property.
</>
Copy
val aFile = File("path/to/file")
aFile.name
The property returns a string value representing the name of the file.
Example
For this example, we will consider a file named info.txt at the path mydata/set1/info.txt
.
In the following program, we programmatically get the file name using File.name property.
Main.kt
</>
Copy
import java.io.File
fun main() {
val filePath = "mydata/set1/info.txt"
val file = File(filePath)
val fileName = file.name
println("File name : $fileName")
}
Output
File name : info.txt
Conclusion
In this Kotlin Tutorial, we learned how to get the name of a file from a file object using File.name property.