How to check empty directory using Java

 Posted On  | Yashwant Chavan 

Sometimes we need to find out that particular directory or folder is empty or not. This tutorial will help you to check whether directory is empty or not using java application.

Here is the simple logic to identify the respected directory or folder is empty or not. First of all we identify the file path is directory or not, If it is directory then we get the array of strings naming the files and directories in the directory using file.list(). If this abstract file does not denote a directory, then this method returns null. Otherwise an array of strings is returned.

If string array length is zero then respected folder is empty otherwise it has files and folders

Java Empty Directory Check Example

package com.technicalkeeda.app;

import java.io.File;

public class JavaEmptyDirectory {
    public static void main(String[] args) {
        System.out.println("Is Empty Directory ? " + isDirectoryEmpty(new File("C:\\article")));
        System.out.println("Is Empty Directory ? " + isDirectoryEmpty(new File("C:\\article\\empty")));

    }

    public static boolean isDirectoryEmpty(File file) {
        if (file != null && file.isDirectory()) {
            return (file.list().length == 0 ? true : false);
        }
        return false;
    }
}

Output

Let us compile and execute the above program.

Is Empty Directory ? false
Is Empty Directory ? true


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0315 seconds.