Search code examples
filekotlindirectorysize

Kotlin recursively get size of a folder


I have seen how to return size of a folder in Java: Get size of folder or file, but I couldn't find it in Kotlin.

How do I get the size of a folder in Kotlin?


Solution

  • To get the total size of files in the directory and its children, recursively, you can use the .walkTopDown() function to build a sequence that enumerates all of the files, and then sum the .lengths of its file elements.

    val directory: File = ...
    
    val totalSize = 
        directory.walkTopDown().filter { it.isFile }.map { it.length() }.sum()
    

    Filtering the elements using .isFile is needed here because it is unspecified what .length returns when called on a File denoting a directory.