Aplicativo para busca de arquivos

2 respostas
danieldestro

Pessoal,

Acabei fazendo um programinha para buscar arquivos que contenham (ou não) alguma palavra (ou seqüência de palavras). A busca é bem simples e pode ser melhorar com algorítmos de match melhores, além do filtro de arquivos poder ser melhorado também. Mas para quem interessar, segue o código:

import java.io.*;
import java.util.Vector;

/**
 * This class searches for the files from a specific directory and its
 * sub-directories that satisfy some conditions like:
 * -> [not] contains the informed text
 * @author daniel destro do carmo 
 */

public class TextFinderApp {

	private static String dirPath = null;
	private static String textToFind = null;
	private static String filesFilter = null;
	private static boolean recursive = false;
	private static boolean mustContainText = true;
	private static boolean matchCase = false;
	private static Vector selectedFiles = new Vector();

	public static void main(String[] args) {		
		//check for the init parameters
		try {
			loadParameters( args );
			if( !matchCase ) {
				//do not match case... make it upper case
				textToFind = textToFind.toUpperCase();
			}
			//go for it!!!
			search();
		}
		catch( Exception e ) {
			e.printStackTrace();
			//exception??? abort it!!!
			return;
		}
		finally {
			//printVariables();
			printFiles();
		}
	}
	
	/**
	 * Search the files according to the parameters defined in the
	 * program execution. It will bring the pathname of the files
	 * that satisfy the desired conditions.
	 * @throws Exception
	 */	
	private static void search() throws Exception {
		File root = new File( dirPath );
		if( !root.isDirectory() ) {
			throw new Exception("This is an invalid root path");
		}
		search( root );
	}
	
	/**
	 * Make the search throught the directories. It can be recursive if
	 * informed during the program execution.
	 * @param directory Directory where to search
	 * @throws Exception
	 */
	private static void search( File directory ) throws Exception {
		File[] files = directory.listFiles();
		if( files==null ) return;
		//go through the directories
		for(int i=0; i<files.length; i++) {
			if( files[i].isDirectory() && recursive ) {
				search( files[i] );
			}
		}
		if(filesFilter==null) {
			//do not use the filter pattern
			for(int i=0; i<files.length; i++) {
				if( files[i].isFile() ) {
					findText( files[i] );
				}
			}
		} else {
			//use the filter pattern
			FilenameFilter ff = new FilenameFilterImpl( filesFilter );
			File[] filteredFiles = directory.listFiles( ff );
			for(int i=0; i<filteredFiles.length; i++) {
				if( filteredFiles[i].isFile() ) {
					findText( filteredFiles[i] );
				}
			}
		}
	}
	
	/**
	 * Find the informed text within the file. It will add
	 * the file to the vector if text is found and the contains
	 * text option is set, otherwise it will add the file to the
	 * vector if the text is not found and the not contains option
	 * is set.
	 * @param file File to search into.
	 * @throws Exception
	 */
	private static void findText( File file ) throws Exception {
		if( !file.isFile() || !file.canRead() ) return;
		InputStream is = null;
		DataInputStream dis = null;
		boolean textFound = false;

		try{
			//open the file for reading
			is = new FileInputStream(file);
			dis = new DataInputStream(is);
			String line = null;
			//get the lines
			while( (line=dis.readLine()) != null ) {
				if( !matchCase ) {
					//do not match case... make it upper case
					line = line.toUpperCase();
				}
				if( line.indexOf(textToFind) >= 0 ) {
					textFound = true;
					if( mustContainText ) {
						//satisfied, add it
						selectedFiles.add( file );
					}
					break;
				}
			} //while()

			if( !mustContainText && !textFound ) {
				//satisfied, add it
				selectedFiles.add( file );
			}
		}
		catch( Exception e ) {
			throw e;
		}
		finally {
			//close input streams
			if( dis!=null) dis.close();
			if( is!=null) is.close();
		}
	}
	
	/**
	 * Load and validate the init parameters.
	 * @param params All parameters passed during the program execution.
	 * @throws Exception
	 */
	private static void loadParameters( String[] params ) throws Exception {
		if( params != null ) {
			for(int i=0; i<params.length; i++ ) {
				if( "-d".equals(params[i]) && i<(params.length-1) ) {
					dirPath = params[++i];
				}
				else if( "-t".equals(params[i]) && i<(params.length-1) ) {
					textToFind = params[++i];
				}
				else if( "-f".equals(params[i]) && i<(params.length-1) ) {
					filesFilter = params[++i];
				}
				else if( "-r".equals(params[i]) ) {
					recursive = true;
				}
				else if( "-c".equals(params[i]) ) {
					mustContainText = true;
				}
				else if( "-nc".equals(params[i]) ) {
					mustContainText = false;
				}
				else if( "-mc".equals(params[i]) ) {
					matchCase = true;
				}
			}
		}
		if( params==null || dirPath==null || textToFind==null ) {
			System.out.println("Please, type the correct sintax as following: ");
			System.out.println("  java TextFinder -d <directory path> -t <text to find> [-f <filter pattern>] [-r] [-c] [-nc]");
			System.out.println("
");
			System.out.println("     -d <directory path> : inform the directoy root where the search will run (mandatory).");
			System.out.println("     -t <text to find> : text to find within the files (mandatory).");
			System.out.println("     -f <filter pattern> : a pattern to filter the files (optional).");
			System.out.println("     -r : indicate if the search is recursive into the deeper directories (optional).");
			System.out.println("     -c : indicate if the file must contain the text (optional). This is a default flag.");
			System.out.println("     -nc : indicate if the file does not contain the text (optional).");
			System.out.println("     -mc : match case.");
			System.out.println("
");			
			throw new Exception("Missing init parameter");
		}
	}
	
	/**
	 * List the class variables in the console. For testing purposes only.
	 */	
	private static void printVariables() {
		System.out.println("dirPath="+dirPath);
		System.out.println("textToFind="+textToFind);
		System.out.println("filesFilter="+filesFilter);
		System.out.println("recursive="+recursive);
		System.out.println("mustContainText="+mustContainText);
		System.out.println("matchCase="+matchCase);
	}
	
	/**
	 * List the files that satisfy the conditions in the console.
	 */	
	private static void printFiles() {
		int i=0;
		while(i<selectedFiles.size()) {
			System.out.println(selectedFiles.get(i).toString());
			i++;
		}
		System.out.println("Total files found: "+i);
	}
	
	private static void updateFiles() {
		int i=0;
		while(i<selectedFiles.size()) {
			try {
				new FileUpdate((File) selectedFiles.get(i));
			} catch( Exception e ) {
				e.printStackTrace();
			}
			i++;
		}
	}
}


/**
 * This class implements a FilenameFilter, intended to filter
 * files listing.
 * @author daniel destro do carmo
 */
class FilenameFilterImpl implements FilenameFilter {
	private String filterPattern = null;
	
	public FilenameFilterImpl(String filterPattern) {
		super();
		this.filterPattern = filterPattern;
	}
	
	public boolean accept(File directory, String filename) {
		//you can optimize this filter if desired.
		if( filename.endsWith(filterPattern) ) return true;
		return false;
	}
}

A única coisa que peço é que publiquem o código alterado (melhorado), caso o façam.

Abraços

2 Respostas

cv1

jgrep! :smiley:

danieldestro

:cry: Perguntar não dói né… heheheheheh, mas já foi!

Valeu :wink:

Criado 29 de setembro de 2003
Ultima resposta 29 de set. de 2003
Respostas 2
Participantes 2