Saturday, November 9, 2019

A Unproblematic Event To Cheque If File Is Empty Inwards Java

One of the readers of my weblog Javarevisited emailed me yesterday nearly how to cheque if a file is empty inwards Java in addition to that's why I am writing this post to demo that using an example. The mutual approach for checking if a file is empty or non is to starting fourth dimension cheque if the file exists or non in addition to so cheque if it contains whatever content, but Java has done that difficult move for you. Well, it's pretty slowly to cheque emptiness for a file inwards Java past times using length() method of the java.io.File class. This method returns null if the file is empty, but the skillful affair is it also returns null if the file doesn't exist. Which agency you lot don't take to cheque if the file exists or not.

Btw, when it comes to deciding the emptiness of file, closed to application mightiness last dissimilar than others. For example, closed to application may take in a file amongst exactly whitespace every bit empty but closed to may not.

The length() method volition non take in them empty, which agency if you lot exactly type infinite bar inwards your file it looks empty but it won't last considered empty past times your Java program.

If you lot convey such requirement so you lot take to lay a especial logic which involves reading the file in addition to analyzing content.

Anyway, inwards this article, I'll explicate to you lot how to cheque if given file is empty inwards Java using a sample program. First, we'll without creating a file.

If you lot remember, File degree is used to stand upwards for both file in addition to directory inwards Java but it's nix but a path. When you lot tell new File("C:\\myfile.txt") it doesn't practise a file but a grip to that path. That's why nosotros tin practise a File object to given path in addition to telephone band its length() method to cheque if the file is empty or not.

After that, we'll practise a novel file in addition to verify again, this fourth dimension also our code should tell the file is empty because fifty-fifty though the file exists, at that topographic point is nix inwards it.

In the final step, we'll write something inwards the file in addition to repeat the process. This fourth dimension our programme should impress the file is non empty.



How to cheque if a file is empty inwards Java? Example 

Without whatever farther ado, hither is our sample Java programme to demonstrate how to cheque if a given file is empty or not.

package tool;  import java.io.File; import java.io.FileWriter; import java.io.IOException;  /**  *   * Influenza A virus subtype H5N1 elementary representative to cheque if file is empty inwards Java  */ public class Hello {    public static void main(String args[]) throws IOException {      // checking if file is empty     // if file doesn't exits so also length() method volition consider     // it empty.     File newFile = new File("cookbook.txt");      if (newFile.length() == 0) {       System.out.println("File is empty ...");     } else {       System.out.println("File is non empty ...");     }      // Now let's practise the file     newFile.createNewFile();      // let's endeavor in ane lawsuit to a greater extent than in addition to cheque if file is nevertheless empty     if (newFile.length() == 0) {       System.out.println("File is empty later creating it...");     } else {       System.out.println("File is non empty later creation...");     }      // Now let's write something on the file     FileWriter author = new FileWriter(newFile);     writer.write("Java is best");     writer.flush();      // don't forget to closed the FileWriter     writer.close();      // Now let's cheque in ane lawsuit to a greater extent than in addition to verify if file is nevertheless empty     if (newFile.length() == 0) {       System.out.println("File is nevertheless empty later writing into it...");     } else {       System.out.println("File is non empty later writing something ...");     }    } }  Output File is empty ... File is empty later creating it... File is not empty later writing something ...

You tin clearly run into that when nosotros starting fourth dimension checked past times creating a File object, nosotros got the File is empty because the file didn't fifty-fifty exist. Remember, a file is non created inwards Java until you lot telephone band the createNewFile()method.

After that, nosotros checked in ane lawsuit to a greater extent than but this fourth dimension also nosotros got the File is empty output because fifty-fifty though the file exists it was genuinely empty, nix was written on it.

In the 3rd case, nosotros writing ane business "Java is great" on file using FileWriter in addition to so checked again. Boom!!!, this fourth dimension the file wasn't empty which agency our code is working fine every bit expected.

You tin also re-create glue this programme inwards your Eclipse IDE in addition to run in addition to it should impress the same output real starting fourth dimension time.

of my weblog Javarevisited emailed me yesterday nearly how to cheque if a file is empty inwards Jav Influenza A virus subtype H5N1 Simple Example to Check if File is Empty inwards Java



But, later that, the output volition alter in addition to it volition ever print:

File is non empty ...
File is non empty later creation...
File is non empty later writing something ...

Can you lot estimate why?

Well, because later the starting fourth dimension run of this program, you lot should already convey a cookbook.txt file inwards your Eclipse's projection directory in addition to it is non empty thence it prints non empty. The createNewFile() method volition non override if a file amongst the same mention already exists.

Another thing, which you lot should continue inwards hear is calling the flush() or close() method later writing something on file. For example, if you lot take the flush() method in addition to cheque if the file is empty or not, you lot may have wrong effect i.e. file is empty, fifty-fifty later you lot convey written something on it.

Can you lot estimate why?

Well, because the content may non last flushed to the file when you lot checked, that's why calling flush() is of import earlier checking.

That's all nearly how to cheque if a file is empty inwards Java. You tin exactly telephone band the length() method without worrying nearly whether the file exists or not. This method returns null if the file doesn't be or file is genuinely empty i.e. doesn't comprise anything.

Further Learning
The Complete Java MasterClass on Udemy
Java Fundamentals Part 1 in addition to ii on Pluarlsight
Extreme Java - Advanced Topics past times Heinz Kabutz
Core Java SE ix for the Impatient (2nd Edition)
10 Things Java Developers Should Learn inwards 2018
10 Books Java Developers Can Read inwards 2018

Thanks for reading this article so far. If you lot similar this article so delight percentage amongst your friends in addition to colleagues. If you lot convey whatever questions or feedback so delight drib a note.

No comments:

Post a Comment