|
@@ -0,0 +1,62 @@
|
|
|
+package com.ruoyi.common.utils;
|
|
|
+
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.util.CollectionUtils;
|
|
|
+
|
|
|
+import java.io.*;
|
|
|
+import java.util.HashSet;
|
|
|
+import java.util.Iterator;
|
|
|
+import java.util.Set;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+public class SensitiveWordUtil {
|
|
|
+ //敏感词库 通过jvm缓存
|
|
|
+ private static final Set<String> sensitiveWords = new HashSet<>();
|
|
|
+
|
|
|
+ static {
|
|
|
+ //静态代码块加载敏感词库
|
|
|
+ load();
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 从敏感文件中逐行读取,加载到敏感词 set中
|
|
|
+ */
|
|
|
+ public static void load() {
|
|
|
+ if (CollectionUtils.isEmpty(sensitiveWords)) {
|
|
|
+ InputStream in = SensitiveWordUtil.class.getResourceAsStream("/word.txt");
|
|
|
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(in));) {
|
|
|
+ String line;
|
|
|
+ //逐行读取文件
|
|
|
+ while ((line = reader.readLine()) != null) {
|
|
|
+ sensitiveWords.add(line);
|
|
|
+ }
|
|
|
+ } catch (FileNotFoundException e) {
|
|
|
+ log.error("读取敏感词库文件错误,文件不存在");
|
|
|
+ throw new RuntimeException("读取敏感词库文件错误,文件不存在");
|
|
|
+ } catch (IOException e) {
|
|
|
+ log.error("读取敏感词库文件错误,io问题");
|
|
|
+ throw new RuntimeException("读取敏感词库文件错误,io问题");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 判断传入文本中是否包含敏感词
|
|
|
+ *
|
|
|
+ * @param word 内容
|
|
|
+ * @return 是否包含敏感词
|
|
|
+ */
|
|
|
+ public static boolean containsSensitiveWord(String word) {
|
|
|
+ Iterator<String> iterator = sensitiveWords.iterator();
|
|
|
+ boolean result = false;
|
|
|
+ while (iterator.hasNext()) {
|
|
|
+ String sensitiveWord = iterator.next();
|
|
|
+ if (word.contains(sensitiveWord)) {
|
|
|
+ result = true;
|
|
|
+ log.error("匹配到敏感词" + sensitiveWord);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+}
|