简体   繁体   中英

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.

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.

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. 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>>;
    }
}

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