首先找到需要过滤的文件资源txt
资源目录
使用spring初始化资源
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.SensitiveUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import java.io.File;
import java.net.URL;
import java.util.List;
/**
* @Author: StephenZhang
* @date: 2021-06-30 17:37
*/
@Component
public class SensitiveWordConfig implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(SensitiveWordConfig.class);
/**
* 初始化敏感词汇
*/
@Override
public void afterPropertiesSet() {
URL path = ResourceUtil.getResource("txtTemplate/synthesize.txt");
File file = FileUtil.file(path);
FileReader reader = new FileReader(file);
SensitiveUtil.init(reader.readLines());
logger.info("initialize bean:{}", SensitiveWordConfig.class.getName());
}
/**
* 敏感词过滤替换***
*/
public static String sensitiveWordFiltering(String text) {
List<String> matchAll = SensitiveUtil.getFindedAllSensitive(text, false, false);
if (matchAll.size() > 0) {
for (String match : matchAll) {
StringBuilder replace = new StringBuilder();
for (int i = 0; i < StrUtil.length(match); i++) {
replace.append("*");
}
text = StrUtil.replace(text, match, replace.toString());
}
}
return text;
}
}
项目使用
SensitiveUtil.containsSensitive(paramVo.getContent());
源码
/**
* 是否包含敏感词
* @param text 文本
* @return 是否包含
*/
public static boolean containsSensitive(String text){
return sensitiveTree.isMatch(text);
}