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

Kotlin – File last modified timestamp

To get the last modified timestamp of a file in Kotlin, we can use lastModifiedTime() function from the java.nio.file.attribute.BasicFileAttributes class.

Steps to get last modified 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 lastModifiedTime() function on the BasicFileAttributes object, which returns the last modified timestamp.
</>
Copy
val filePath = Paths.get("path/to/file")
val attributes: BasicFileAttributes = Files.readAttributes(filePath, BasicFileAttributes::class.java)
val lastModifiedTime = attributes.lastModifiedTime()

Example

In the following program, we get the last modified timestamp of a text file: info.txt.

Main.kt

</>
Copy
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 lastModifiedTime = attributes.lastModifiedTime()
    println(lastModifiedTime)
}

Output

2023-03-23T05:31:31.160258Z

Conclusion

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