所以我一直在试图让这个工作一段时间。让我先说这个,说我不是程序员。最近我接受了这更多的爱好。我一直试图让2个文本文件逐行搜索。即One有一串单词(大约10个,每行一个),另一个单词也有多个(接近500个)。我希望我的程序能够说出较小文本文件中的每个单词在较大文本文件中出现的次数。我到目前为止是:使用一个文本文件来搜索另一个文本文件
import java.util.Scanner;
import java.io.File;
import java.util.regex.Pattern;
public class StringSearch
{
public static void main (String args[]) throws java.io.IOException
{
int tot = 0;
Scanner scan = null;
Scanner scan2 = null;
String str = null;
String str2 = null;
File file = new File("C:\\sample2.txt");
File file2 = new File("C:\\sample3.txt");
scan = new Scanner(file);
scan2 = new Scanner(file2);
while (scan.hasNextLine())
{
str = scan.nextLine();
tot = 0;
while (scan2.hasNextLine())
{
str2 = scan2.nextLine();
if(str.equals(str2))
{
tot++;
}
}
System.out.println("The String = " + str + " and it occurred " + tot + " times");
}
}
}
不知道为什么这不工作。它读取第一个文本文件中的第一个单词,并计算它在第二个文本文件中出现的次数,但是它只是停止并且不移动第一个文件中的第二个单词。我希望这是有道理的。我认为第二个循环有些问题,但我不知道是什么。
所以,任何帮助将不胜感激。我希望能够在未来发挥作用并转向更复杂的项目。要开始正确的地方?
干杯家伙
如果将第一个文件的所有单词加载到数组中,则只需从第二个文件中读取数据,并将其与数组内容进行比较。单词的数量足够小,不会占用太多内存,而且您只处理一个文件。 – 2013-08-06 12:50:53
注意,使用shell:'fgrep -f sample2.txt sample3.txt' –