Check if a file is empty in Java
This post will discuss how to check if a file is empty in Java.
1. Using BufferedReader.readLine() method
A simple solution is to get a character-input stream from BufferedReader using the readLine() method. It returns null if the end of the stream has been reached without reading any characters. This can be used to check if a file is empty, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { File file = new File("/data/app.log"); try { BufferedReader br = new BufferedReader(new FileReader(file)); if (br.readLine() == null) { System.out.println("File is empty"); } } catch (IOException e) { e.printStackTrace(); } } } |
2. Using Apache Commons IO
With Apache Commons IO, you can use the FileUtils.readFileToString() method that reads the content of any file into a string. Then you can simply check if the string is empty or not. If the string is empty, the file must be empty, otherwise not.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; public class Main { public static void main(String[] args) { File file = new File("/data/app.log"); try { if (FileUtils.readFileToString(file, Charset.defaultCharset()).isEmpty()) { System.out.println("File is empty"); } } catch (IOException e) { e.printStackTrace(); } } } |
3. Using File.length() method
Another option is to create the File instance and call its length() method to get the length of the file. If the file is empty, its length must be 0. But the opposite might not be true, since the length() method returns 0 if the file does not exist, is a directory, or any other I/O exception happens.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.io.File; public class Main { public static void main(String[] args) { File file = new File("/data/app.log"); if (file.length() == 0L) { System.out.println("File is empty"); } } } |
That’s all about checking if a file is empty in Java.
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 :)