无线&移动互联网技术研发

换位思考·····
posts - 19, comments - 53, trackbacks - 0, articles - 283
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

java 过滤敏感词

Posted on 2009-07-26 22:42 Gavin.lee 阅读(1408) 评论(0)  编辑  收藏 所属分类: java SE & EE
就目前来说,我项目里用的是直接封装需要过滤的词,到一个数组,然后将输入串进行匹配,当相等时,就过滤掉。这种做法太呆板了,根本没什么含量,今天在网上无意中看到这个工具类,感觉不错,有点思想,改天有时间研究下,将我现项目里过滤给替换掉。呵,先放着了。
words.properties
Properties
属性

package com.Gavin.wap;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class KeywordFilter {
    
private static Pattern pattern = null;

    
public static void initPattern() {
        StringBuffer patternBuf 
= new StringBuffer();
        
try {
            InputStream in 
= KeywordFilter.class.getClassLoader().getResourceAsStream("words.properties");
            Properties properties 
= new Properties();
            properties.load(in);
            
            Enumeration<?> enu 
= properties.propertyNames();
            
while (enu.hasMoreElements()) {
                patternBuf.append((String) enu.nextElement() 
+ "|");    //读取所有properties里的词,以 | 分隔
            }

            
            patternBuf.deleteCharAt(patternBuf.length() 
- 1);
            
            
//默认下,properties文件读取编码: ISO8859-1
            pattern = Pattern.compile(new String(patternBuf.toString().getBytes("ISO-8859-1"), "UTF-8"));
            
        }
 catch (IOException e) {
            e.printStackTrace();
        }

    }


    
public static String doFilter(String str) {
        System.out.println(
"str:" + str);
        
try {
            Matcher m 
= pattern.matcher(str);
            str 
= m.replaceAll("*");
        }
 catch (Exception e) {
            e.printStackTrace();
        }

        
return str;
    }


    
public static void main(String[] args) {
        String str 
= "Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。";
        initPattern();
        
        
try {
            System.out.println(KeywordFilter.doFilter(str));
        }
 catch (Exception e) {
            e.printStackTrace();
        }

    }


}


只有注册用户登录后才能发表评论。


网站导航: