Search in files in a directory

3

I have a small application that needs a search engine that can list files that contain a user-entered term.

The first feature of the program, which is responsible for reporting how many times a string appears within a .txt file, is already complete.

Here is the code for the first part:

Teclado teclado= new Teclado();

String opcao= teclado.getUserInput("Insira uma palavra: "); 

BufferedReader br= new BufferedReader(
        new InputStreamReader(
                new FileInputStream("arquivo.txt")));

String linha= br.readLine();
int count=0;
while(linha != null){
    String palavras[] = linha.split(" ");
    for(int i=0; i<palavras.length; i++){
        //System.out.println(palavras[i]);

        if(opcao.equalsIgnoreCase(palavras[i])){  
            count++;  

        }  
    }
    linha= br.readLine();
}

System.out.println(count);

Could anyone give me a light on how to implement this search engine?

    
asked by anonymous 19.06.2015 / 14:59

1 answer

4

I was able to resolve:

/*
     * Lista arquivos de um determinado diretório.
     */
    String dir= teclado.getUserInput("Insira o diretório: "); 

    File diretorio = new File(dir); 
    File[] arquivos = diretorio.listFiles(); 

    if(arquivos != null){ 
        int length = arquivos.length; 

        for(int i= 0; i< length; i++){ 
            File arquivo = arquivos[i]; 

            if(arquivo.isFile()){  


                /*
                 * Verifica palavras dos arquivos
                 */

                BufferedReader br_d= new BufferedReader(
                        new InputStreamReader(
                                new FileInputStream(arquivo)));
                String linha_d= br_d.readLine();
                int count_d=0;  
                while(linha_d != null){
                    String palavras_d[] = linha_d.split(" ");
                    for(int i_d=0; i_d<palavras_d.length; i_d++){
                        //System.out.println(palavras[i]);

                        if(opcao.equalsIgnoreCase(palavras_d[i_d])){  
                            count_d++;  

                        }  
                    }
                    linha_d= br_d.readLine();
                }
                if(count_d != 0){
                    System.out.println(arquivo.getName()); 
                    System.out.println(count_d);
                }


                /*
                 * FIM
                 */
            } 
            else 
                if(arquivo.isDirectory()){ 
                System.out.println("Diretorio: " + arquivo.getName()); 
            } 
        } 
    }  

Now I just need a more refined search to list only .txt files, but otherwise everything beauty. :)

    
19.06.2015 / 16:09