Monday, October 31, 2011

Getting list of files/subdirectories in a directory

The following code 'll return the list of files that are present in the directory.This function accepts a parameter 'dirName',the directory in which you want the list of files.
  1. public String[] filesInDir(String dirName){
  2.   String[] files = null;  
  3.   try {
  4.     File dir = new File(dirName);
  5.     if (dir.isDirectory()) {
  6.       files = dir.list();
  7.     }
  8.     else if (!dir.exists()){
  9.       System.out.println("Directory doesn't exist");
  10.       System.exit(0);
  11.    }
  12.    } catch (Exception e) {
  13.      e.printStackTrace();
  14.    }  
  15.   return files;
  16. }

No comments:

Post a Comment