简体   繁体   English

Java用BufferedReader比较文件

[英]Java comparing files with BufferedReader

This is the method I'm trying to do: 这是我要尝试的方法:

static void filter( BufferedReader orders, BufferedReader in,
        BufferedWriter out ) throws IOException

The objective is to read a text file with the in reader, then check if the sentences contain the keywords that are stored in another text file with the orders reader, and if the sentences do contain those key words, write them down in another text file with out writer. 目的是使用in阅读器阅读文本文件,然后使用订单阅读器检查句子中是否包含存储在另一个文本文件中的关键字,如果句子中确实包含这些关键字,则将其写下来在另一个文本文件中没有作家。

I have done this so far: 到目前为止,我已经做到了:

static void filter( BufferedReader orders, BufferedReader in,
        BufferedWriter out ) throws IOException{

    BufferedReader ordersf = new BufferedReader(new FileReader("order_filter.txt"));
    BufferedReader inf = new BufferedReader(new FileReader("hamlet.txt"));
    BufferedWriter outf = new BufferedWriter(new FileWriter("out_filter.txt"));

    String line = inf.readLine();

    while(line != null){
        String filter = ordersf.readLine();
        if(filter.equals(line))
            outf.write("    "+line);
    }
    ordersf.close();
    inf.close();
    outf.close();
}

Now I have no clue on how to compare the key words contained in order_filter.txt with the sentences in hamlet.txt I would appreciate some help. 现在,我对如何比较包含的关键词不知道order_filter.txt在句子hamlet.txt我希望得到一些帮助。

If you wanted to do it the dirty way then you can split the words from ordersf and see if each word is a substring of the sentence. 如果您想以肮脏的方式进行操作,则可以从ordersf中拆分单词,然后查看每个单词是否是句子的子字符串。 So assuming your filter has words delimited by spaces then you could do something like: 因此,假设您的过滤器包含由空格分隔的单词,那么您可以执行以下操作:

String[] filter_words = filter.split(" ");

for(String filter_word : filter_words) {
    if(line.toLowerCase().contains(filter_word.toLowerCase())) {
        <<do something>>;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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