我想制作一个小型搜索引擎。考虑我有5个文本文件,我想在整个文件中找到“book”这个词。我该如何开始?我是一名大四学生,我有一些关于树和迭代器的信息,我必须使用这些概念。任何人都可以帮我提供代码吗?
答案 0 :(得分:0)
您不需要任何有关树和迭代器的知识。这完全是关于递归调用,不再是。
这是纯Java代码,没有使用依赖项或框架: 只需传递您想要在调用时搜索的目录或文件名和单词。
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;
}
}
我只是想知道什么是目的?个人教育?