简体   繁体   中英

how to make a small search engine in java

I want to make a small search engine.consider that I have 5 text files and I want to find the word "book" in whole files.How should i start? I am a senior and I have a little information about trees and iterators and I have to use these concepts.could anyone help me with the code?

You do not need any knowledge about trees and iterators. It is all about recursive calls, no more.

Here is the pure Java code with no dependencies or frameworks used: just pass directory or file name and word you'd like to search as parameters when call it.

package com.mytests;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class Sometest {

public static void main(String[] args) {

    if (null == args || args.length < 2) {
        System.err.println("Not enough parameters. Please provide searchPath and searchWord.");
        return;
    }

    String pathToSearch = args[0];
    String wordToSearch = args[1];

    System.out.println("Start search word " + wordToSearch + " in " + pathToSearch);

    File searchFile = new File(pathToSearch);

    if (!searchFile.exists()) {
        System.err.println("Cannot find given file or directory to search :" + pathToSearch + ": ");
    }

    int matchesCount = 0;
    matchesCount = searchWord(searchFile, wordToSearch, matchesCount);

    System.out.println("Search completed. Matches found : " + matchesCount);

}

private static int searchWord(File sourceFile, String wordToSearch, int matchesCount) {

    int count = matchesCount;
    if (sourceFile.isDirectory()) {
        String[] sourceFilesArray = sourceFile.list();

        for (String nextFileName : sourceFilesArray) {
            File nextFile = new File(sourceFile.getAbsolutePath() + System.getProperty("file.separator")
                    + nextFileName);
            count = searchWord(nextFile, wordToSearch, count);
        }
    } else {
        try {
            BufferedReader sourceFileReader = new BufferedReader(new FileReader(sourceFile));
            String nextLine = "";
            while (true) {
                nextLine = sourceFileReader.readLine();
                if (null == nextLine) {
                    break;
                }

                if (nextLine.contains(wordToSearch)) {
                    System.out.println("found in -> " + sourceFile.getCanonicalPath());
                    count++;
                }

            }
            sourceFileReader.close();
        } catch (Exception e) {
            System.err.println("Error while reading file " + sourceFile.getAbsolutePath() + " : " + e.getMessage());
        }
    }

    return count;
}

}

I'm just wondering what is a purpose? personal education?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM