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

Kotlin – File Size

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

Steps to get the size 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 size() function on the BasicFileAttributes object, which returns the size of the file in bytes.
</>
Copy
val filePath = Paths.get("pat/to/file")
val attributes: BasicFileAttributes = Files.readAttributes(filePath, BasicFileAttributes::class.java)
val fileSize = attributes.size()

Example

In the following program, we get the size of a text file: info.txt programmatically using Kotlin.

Kotlin - File Size

The size of the file is 12 bytes.

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 fileSize = attributes.size()
    println("File size : $fileSize bytes")
}

Output

File size : 12 bytes

Conclusion

In this Kotlin Tutorial, we learned how to get the size of a file in bytes using java.nio.file.attribute.BasicFileAttributes.size() function.