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?
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 .length
s 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.
So here is how to do it :
private fun dirSize(dir: File): Long {
if (dir.exists()) {
var result: Long = 0
val fileList = dir.listFiles()
for (i in fileList!!.indices) {
if (fileList[i].isDirectory) {
result += dirSize(fileList[i])
} else {
result += fileList[i].length()
}
}
return result
}
return 0
}
And if you want a readable string your can do this :
private fun getStringSize(size: Long): String {
if (size <= 0)
return "0MB"
val units = arrayOf("B", "KB", "MB", "GB", "TB")
val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()
return DecimalFormat("#,##0.#").format(size / Math.pow(1024.0, digitGroups.toDouble())) + " " + units[digitGroups]
}
How to use it :
val directory = File(filesDir.absolutePath + File.separator + DIRECTORY_NAME)
println(getStringSize(dirSize(directory)))
Hope it's will help some of you.