Kotlin – Get File Creation Date

Kotlin – Get File Creation Date

To get the creation date of a file in Kotlin, you can use the Files class from the java.nio.file package. This class provides a method Files.readAttributes() to access the file’s attributes, including its creation time.

This tutorial will show you how to retrieve the creation date of a file in Kotlin.

Steps to Get the File Creation Date in Kotlin

Here’s how to get the file creation date in Kotlin:

  1. Import the Files class and the Path class from the java.nio.file package.
  2. Convert the file path to a Path object.
  3. Use the Files.readAttributes() method to retrieve the file attributes.
  4. Access the creation time from the attributes using creationTime() on the attributes object.

Kotlin Example Program to Get File Creation Date

In the following example, we demonstrate how to retrieve the creation date of a file named 'example.txt'.

Main.kt

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

fun main() {
    val filePath = Paths.get("example.txt") // Replace with your file path

    val attrs = Files.readAttributes(filePath, BasicFileAttributes::class.java)
    val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val creationDate = formatter.format(attrs.creationTime().toMillis())

    println("The creation date of the file is: $creationDate")
}

Output

The creation date of the file is: 2023-10-24 19:19:04

The output will display the creation date of the specified file, formatted as “year-month-day hour:minute:second”.

Summary

In this Kotlin tutorial, we covered how to retrieve the file creation date using the attributes of the file, with an example.