JavaUtilS | 敏感词过滤 - SensitiveWord

package com.yidianqn.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 敏感词过滤类
 *
 * @author java
 */
public class SensitiveWord {

    /**
     * 敏感词转化为字符串数组
     */
    private static final String[] str = readFile().split(",");

    /**
     * 敏感词库路径
     */
    private static final String pathName = "static/file/CensorWords.txt";

    /**
     * @Description 将敏感词全部替换为等长度的"*"号。
     */
    public static String outWords(String put) {
        for (int i = 0; i < str.length; i++) {
            if (put.contains(str[i])) {
                StringBuilder text = new StringBuilder();
                for (int j = 0; j < str[i].length(); j++) {
                    text.append("*");
                }
                put = put.replace(str[i], text);
            }
        }
        return put;
    }

    /**
     * @Description 返回是否有敏感词
     */
    public static boolean isSensitive(String put) {
        boolean status = false;
        for (int i = 0; i < str.length; i++) {
            if(put.contains(str[i])) {
                status=true;
                break;
            }
        }
        return status;
    }

    /**
     * @Description 读入TXT文件
     */
    private static String readFile() {
        StringBuilder sb=new StringBuilder();

        try {
            InputStream in = SensitiveWord.class.getClassLoader().getResourceAsStream(pathName);
//            InputStream in = new FileInputStream(resource.getFilename());
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据//该步即不会第一位有逗号,也防止最后一位拼接逗号!
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(line);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        String msg = "一起来学 SpringBoot 2.x | 第八篇:通用 Mapper 与分页插件的集成一起来学 SpringBoot 2.x | 第八篇:通用 Mapper 与分页插件的集成";
//        System.out.println(isSensitive("一起来学 SpringBoot 2.x | 第八篇:通用 Mapper 与分页插件的集成一起来学 SpringBoot 2.x | 第八篇:通用 Mapper 与分页插件的集成"));
        outWords(msg);
        long l1 = System.currentTimeMillis() - l;
        System.out.println(l1);
    }

}

 

你可能感兴趣的:(JavaUtilS)