Skip to main content

How to get the last modified timestamp of a file in Kotlin

How to get the last modified timestamp of a file in Kotlin.

Here's a step-by-step tutorial on how to get the last modified timestamp of a file in Kotlin.

Step 1: Import the necessary classes and functions

To get started, you need to import the required classes and functions from the Java standard library. Add the following import statement at the beginning of your Kotlin file:

import java.io.File
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.FileSystems
import java.nio.file.Files

Step 2: Define the file path

Next, you need to define the path to the file whose last modified timestamp you want to retrieve. You can do this by creating an instance of the File class and passing the file path as a string argument. Replace "path/to/your/file" with the actual file path:

val filePath = "path/to/your/file"
val file = File(filePath)

Step 3: Get the file's last modified timestamp

To get the last modified timestamp of the file, you can use the BasicFileAttributes class from the java.nio.file.attribute package. This class provides various file attributes, including the last modified timestamp. Here's how you can retrieve it:

val path = FileSystems.getDefault().getPath(filePath)
val attributes = Files.readAttributes(path, BasicFileAttributes::class.java)
val lastModifiedTime = attributes.lastModifiedTime().toMillis()

In the above code, we create a Path object using FileSystems.getDefault().getPath(filePath) and then use the Files.readAttributes() function to retrieve the file attributes. We pass BasicFileAttributes::class.java as the second argument to specify that we want to retrieve the basic file attributes. Finally, we use the lastModifiedTime() function to get the last modified timestamp, and toMillis() to convert it to milliseconds.

Step 4: Display the last modified timestamp

To display the last modified timestamp, you can simply print it to the console using the println() function:

println("Last modified timestamp: $lastModifiedTime")

Complete code example: Here's the complete code example that puts everything together:

import java.io.File
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.FileSystems
import java.nio.file.Files

fun main() {
val filePath = "path/to/your/file"
val file = File(filePath)

val path = FileSystems.getDefault().getPath(filePath)
val attributes = Files.readAttributes(path, BasicFileAttributes::class.java)
val lastModifiedTime = attributes.lastModifiedTime().toMillis()

println("Last modified timestamp: $lastModifiedTime")
}

Make sure to replace "path/to/your/file" with the actual file path before running the code.

That's it! You have successfully retrieved the last modified timestamp of a file in Kotlin.