Friday, 31 October 2014

How to check if directory is empty in JAVA

Standard


In file class we have method called list() it Returns an array of strings naming the files and directories
 in the directory denoted by this abstract pathname.So by checking with length we can say directory
is empty or not. Let's go for code..













----------------------------------------------------------------------------------------------------------------------------------



JAVA CODE :




  1. package com.system;  
  2.   
  3. import java.io.File;  
  4.   
  5. public class Test  
  6. {  
  7.     public static void main(String[] args)  
  8.     {   
  9.    
  10.  File file = new File("D:\\newfolder");  
  11.         
  12.  long n=file.list().length;  
  13.         
  14.       System.out.println("Total files"+n);  
  15.  if(file.isDirectory()){  
  16.    
  17.   if(file.list().length>0){  
  18.    
  19.    System.out.println("Directory is not empty!!!!");  
  20.    
  21.   }else{  
  22.    
  23.    System.out.println("Directory is empty!!!!");  
  24.    
  25.   }  
  26.    
  27.  }else{  
  28.    
  29.   System.out.println("This is not a directory");  
  30.    
  31.  }  
  32.     }  
  33. }  

0 comments:

Post a Comment