Loading
Java Search in File Systems

Java Quick Notes

Refresh Your Java - Before Java Interview

We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

Go to SiteMap

Q)  Java Search in File Systems


Ans)

This example illustates how to seach for a
given file in given directory.

import java.io.*;
import java.util.ArrayList;

public class SearchFileSystem{

  //Search all file roots (c:, d:, etc.)
  //Modified to return List of files

  ArrayList files = new ArrayList();

  public ArrayList searchFile(String name) throws Exception { 
  File[] roots = File.listRoots();
  if(roots != null) {
    for (int i = 0 ; i < roots.length ; i++) {   
 ArrayList aux = recursiveSearch(roots[i], name);
    if (aux != null && aux.contains(name)) {  
          files.add(roots[i].getCanonicalPath());     
        }    
     }
   }
   return files; 
  }

  //Search from specified root
  //Modified to return List of files

  public ArrayList recursiveSearch(File f, String name) throws Exception {  
  if(f.exists()) {
   File[] childs = f.listFiles();
   if(childs != null) { 
    for (int i = 0 ;i < childs.length ; i++) {   
      if (childs[i].isDirectory()) { 
       ArrayList aux = recursiveSearch(childs[i], name);   
       if (aux != null && aux.contains(name)) {  
         files.add(childs[i].getCanonicalPath());     
       }   
      } else if (name.compareTo(childs[i].getName()) == 0) {  
         files.add(childs[i].getCanonicalPath());        
      } 
     } 
    }
   }
   return files;
  }
 
}



Back to top

------------------------- We hope you got necessary Info On -----------------------------------------

Java Search in File Systems


Java Search in File Systems

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



Face Book
Request for a Mock Interview/Training

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free