找出两个文件中相同的单词(java实现)

2020-08-24 11:50:14 浏览数 (1)

代码语言:javascript复制
package com.zy.DesignPrinciples.singleresponsibility;


import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;

/**
 * @ClassName: ReaderComplete
 * @Author: Tiger
 * @Title: 找出两个文件中相同的单词
 * @Datetime: 2020/8/19   19:49
 * @Package: com.zy.DesignPrinciples.singleresponsibility
 */
public class ReaderComplete {
    public static void main(String[] args) throws Exception {
        String s = loadFile("F:\.temp\1.txt");
        String s1 = loadFile("F:\.temp\2.txt");
        String[] words1 = parseWordsFromString(s);
        String[] words2 = parseWordsFromString(s1);
        String[] words = findTheSameWords(words1, words2);
        for (String word : words) {
            System.out.println(word);
        }
    }

    //加载文件内容,并将文本内容解析返回出去
    public static String loadFile(String path) throws Exception {
        FileReader reader = new FileReader(path);
        //bufferedReader 一次只能读一行内容
        BufferedReader br = new BufferedReader(reader);
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {

            sb.append(line);
            sb.append("n");
        }
        br.close();
        return sb.toString();
    }
    //将解析的内容变成数组
    public static String[] parseWordsFromString(String string) {
        String[] strings = string.split("[^a-zA-Z] ");
        return strings;

    }
    //查询两文件的相同代码
    public static String[] findTheSameWords(String[] s1,String[] s2){
        HashSet<String> set = new HashSet<>();
        for (int i = 0; i < s1.length; i  ) {
            for (int j = 0; j < s2.length; j  ) {
                if (s1[i].equals(s2[j])){
                    set.add(s1[i]);
                }
            }
        }
        return  set.toArray(new String[] {});
    }
}

第二种比较单词的方法:将string【】数组转换成集合,通过集合的retainAll()方法 两个集合取交集

代码语言:javascript复制
public static String[] findTheSameWords2(String[] s1,String[] s2){

        //将字符串数组转换成集合
        List<String> list = new ArrayList(Arrays.asList(s1));
        List<String> list2 = new ArrayList(Arrays.asList(s2));
        //计算交集 并且把计算结果存入到list中而且list2并不会改变
        list.retainAll(list2);
        HashSet<String> set = new HashSet<>(list);
        return set.toArray(new String[] {});
    }

0 人点赞