Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to check if a file is empty in Java on Windows

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!"); 
like image 399
GPX Avatar asked Aug 25 '11 12:08

GPX


People also ask

How can I check if a file is empty?

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.

Can we have empty Java file?

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.

How do you check if a file is in a folder Java?

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.


1 Answers

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"); } 
like image 58
Victor Carmouze Avatar answered Sep 22 '22 21:09

Victor Carmouze