开发者

counting the number of document containing a specific term

lets say i has a term ' about'.

I wanted to know whether a text file contain this word.

If yes, it will increment the number of text 开发者_如何学Gofile containing the word by 1 in a counter.

Any advice on how to do this ?


// class declaration ...
private static String readFile(String fileName) {
    String data = "";
    try {
        BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
        StringBuilder string = new StringBuilder();
        for (String line = ""; line = in.readLine(); line != null)
            string.append(line).append("\n");
        in.close();
        data = line.toString();
    }
    catch (IOException ioe) {
        System.err.println("Oops: " + ioe.getMessage());
    }
    return data;
}

public int filesContaining(String phrase, String... files) {
    int count = 0;
    for (String file : files) {
        if (readFile(file).contains(phrase))
            count++;
    }
    return count;
}

Then use it like:

int count = classInstance.filesContaining("about", "file1.txt", "file2.txt", "file3.txt");

And it returns how many of file1, file2, and file3 contain the word "about".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜