Find file’s size in bytes in Kotlin
This post will discuss how to find a file’s size in bytes in Kotlin.
1. Using Files.size() function
The recommended approach for getting the size of a file in bytes is using the Files.size() function. Note that the returned file size might be different from the actual file size, due to compression, support for sparse files, etc.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.IOException import java.nio.file.Files import java.nio.file.Path fun main() { val path = Path.of("/var/system.logs") try { val size = Files.size(path) println("The file size is $size bytes") } catch (e: IOException) { e.printStackTrace() } } |
2. Using File#length() function
Another approach is to use the File#length() function that returns the length of the file in bytes. If the file is a directory or some I/O occurs, the result is 0.
|
1 2 3 4 5 6 7 |
import java.io.File fun main() { val file = File("/var/system.logs") val size = file.length() println("The file size is $size bytes") } |
3. Using FileChannel#size() function
Another plausible way is to get the associated file channel for the file input stream and call its size() function that returns the current size of the channel’s file in bytes.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.File import java.io.FileInputStream import java.io.IOException fun main() { val file = File("/var/system.logs") try { FileInputStream(file).use { println("The file size is $it.channel.size() bytes") } } catch (e: IOException) { e.printStackTrace() } } |
All the above solutions return the file size in bytes. If you need the file size in Kilobytes (KB), just divide the length by 1024. Similarly, to get the file size in Megabytes (MB), divide the result by 1024 * 1024.
That’s all about finding a file’s size in bytes in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)