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.

Download Code

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.

Download Code

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.

Download Code

 
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.