I am trying to check if a log file is empty (meaning no errors) or not, in Java, on Windows. I have tried using 2 methods so far.
Method 1 (Failure)
FileInputStream fis = new FileInputStream(new File(sLogFilename)); int iByteCount = fis.read(); if (iByteCount == -1) System.out.println("NO ERRORS!"); else System.out.println("SOME ERRORS!");
Method 2 (Failure)
File logFile = new File(sLogFilename); if(logFile.length() == 0) System.out.println("NO ERRORS!"); else System.out.println("SOME ERRORS!");
Now both these methods fail at times when the log file is empty (has no content), yet the file size is not zero (2 bytes).
What is the most efficient and accurate method to check if the file is empty? I asked for efficiency, as I have to keep checking the file size thousands of times, in a loop.
Note: The file size would hover around a few to 10 KB only!
Method 3 (Failure)
Following @Cygnusx1's suggestion, I had tried using a FileReader
too, without success. Here's the snippet, if anyone's interested.
Reader reader = new FileReader(sLogFilename); int readSize = reader.read(); if (readSize == -1) System.out.println("NO ERRORS!"); else System.out.println("SOME ERRORS!");
You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.
It is actually possible to create (at least with OpenJDK 1.6) an empty file and compile it, but: 1. it won't generate a . class file and 2. it won't generate warnings.
To test to see if a file or directory exists, use the “ exists() ” method of the Java java. io. File class. If the exists() method returns true then the file or directory does exist and otherwise does not exists.
Check if the first line of file is empty:
BufferedReader br = new BufferedReader(new FileReader("path_to_some_file")); if (br.readLine() == null) { System.out.println("No errors, and file empty"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With