欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java过滤关键字

程序员文章站 2022-05-18 19:35:52
...
KeywordFilter.java:

1. import java.io.InputStream;
2. import java.util.Enumeration;
3. import java.util.Properties;
4. import java.util.regex.Matcher;
5. import java.util.regex.Pattern;
6.
7. public class KeywordFilter
8. {
9. private static Pattern pattern = null;
10.
11. private static KeywordFilter filter = new KeywordFilter();
12.
13. public static KeywordFilter getInstance()
14. {
15. return (null == filter)?new KeywordFilter():filter;
16. }
17.
18. private KeywordFilter()
19. {
20. init();
21. }
22.
23. private void init()
24. {
25. StringBuilder stringBuilder = new StringBuilder();
26.
27. try
28. {
29. InputStream in = KeywordFilter.class
30. .getResourceAsStream("keyword.properties");
31.
32. Properties pro = new Properties();
33.
34. //Thread.sleep(5000);
35.
36. pro.load(in);
37.
38. Enumeration<?> enu = pro.propertyNames();
39.
40. while (enu.hasMoreElements())
41. {
42. stringBuilder.append(enu.nextElement() + "|");
43. }
44.
45. stringBuilder.deleteCharAt(stringBuilder.length() - 1);
46.
47. pattern = Pattern.compile(new String(stringBuilder.toString()
48. .getBytes("ISO-8859-1"), "UTF-8"));
49.
50. } catch (Exception ex)
51. {
52. ex.printStackTrace();
53. }
54. }
55.
56. public String doFilter(String str)
57. {
58. Matcher m = pattern.matcher(str);
59.
60. str = m.replaceAll("***");
61.
62. return str;
63. }
64.
65. }


keyword.properties文件放在同一目录下,其内容就是要屏蔽的词语的集合,每个词语用“|”分割

如下

暴力|血腥
相关标签: Java thread