Check whether a file is empty in Kotlin
This post will discuss how to check whether a file is empty in Kotlin.
1. Using BufferedReader.readLine() function
The readLine() function of the BufferedReader class returns null if the end of the stream is reached without reading any characters. We can use this to check whether a file is empty, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.BufferedReader import java.io.File import java.io.FileReader import java.io.IOException fun main() { val file = File("/data/app.log") try { val br = BufferedReader(FileReader(file)) if (br.readLine() == null) { println("File is empty") } } catch (e: IOException) { e.printStackTrace() } } |
2. Using File.length() function
Another alternative is to construct the File object and call its length() function to get the file’s length. The file is empty if and only if its length is 0.
|
1 2 3 4 5 6 7 8 |
import java.io.File fun main() { val file = File("/data/app.log") if (file.length() == 0L) { println("File is empty") } } |
This approach is not recommended since the length() function returns 0 even when the file does not exist, is a directory, or an I/O error occurs.
That’s all about checking whether a file is empty 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 :)