In this tutorial, you shall learn how to get the created timestamp of a given file in Kotlin, using BasicFileAttributes class, with example programs.

Kotlin – File creation timestamp

To get the file creation timestamp in Kotlin, we can use creationTime() function from the java.nio.file.attribute.BasicFileAttributes class.

Steps to get created timestamp of a file

  1. Consider that we are given a file identified by a path.
  2. Create a Path object from given file path.
  3. Call Files.readAttributes() function and pass the path object as argument, which returns BasicFileAttributes object.
  4. Call creationTime() function on this BasicFileAttributes object, which returns the file created date timestamp.
val filePath = Paths.get("path/to/file")
val attributes: BasicFileAttributes = Files.readAttributes(filePath, BasicFileAttributes::class.java)
val creationTime = attributes.creationTime()
ADVERTISEMENT

Example

In the following program, we get the creation timestamp of info.txt file.

Main.kt

import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes

fun main() {
    val filePath = Paths.get("info.txt")
    val attributes: BasicFileAttributes = Files.readAttributes(filePath, BasicFileAttributes::class.java)
    val creationTime = attributes.creationTime()
    println(creationTime)
}

Output

2023-03-23T05:31:18Z

Conclusion

In this Kotlin Tutorial, we learned how to get the creation timestamp of a file using java.nio.file.attribute.BasicFileAttributes.creationTime() function.