Sunday, September 25, 2011

search a File in root directorys

/*
This programe searches the given file Which is in "C-directory" only in sub floders also
and also displys the all files and floders in directory and thair path also
if the u want to seach in the anether dir for that change the dir name in the programe
*/
import java.io.*;
public class FileSearch {

public void search( String path,String searchfile) {
File file = new File( path );
File[] filelist = file.listFiles();

for ( File f : filelist ) {
if ( f.isDirectory() ) {
search( f.getAbsolutePath(),searchfile );
System.out.println( "Directory:" + f.getAbsoluteFile() );
if(f.getName().equals(searchfile)){
System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< break;
}
}
else {
System.out.println("------------------------------");
System.out.println( "File:" + f.getAbsoluteFile() );
if(f.getName().equals(searchfile)){
System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< break;
}
}
}
}
public static void main(String[] args) {
FileSearch fs = new FileSearch();
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("press ENTER or enter the file name with extention");
String searchfile=br.readLine();


File[] dir=File.listRoots();
/*
for(int j=0;j<=dir.length;j++)
{
System.out.println(dir[j]);
fs.search(dir[j],searchfile);
}
*/

fs.search("C:/",searchfile); //call the function
}
catch(NullPointerException e)
{
System.out.println("enter abs file "+e);
}
catch(IOException e)
{
System.out.println("enter abs file "+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("error "+e);
}
catch(Exception e)
{
System.out.println("enter abs file "+e);
}
finally{
System.out.println("you get null pointer if the file not get or not specifiy the absolute dir");
System.out.println("----------------------------------------------------------------------------");
fs=null;
}
}
static{
System.out.println("----------------------------------------------------------------------------");
System.out.println("please enter the file in the c dir only");
System.out.println("----------------------------------------------------------------------------");
}
}