功能非常強大的敏感字符處理Java類
敏感字符的處理,性能非常好,采用文件的方式,可通過代碼增加敏感詞等強大的功能
依賴apache的io 和lang包
package com.wiker; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.StringUtils; /** * 敏感字詞處理類 * @author Wiker * @date 2010-1-11 下午10:51:30 */ public class BadWord { private final static File wordfilter = new File("C:/wordfilter.txt"); private static long lastModified = 0L; private static List<String> words = new ArrayList<String>(); private static void checkReload(){ if(wordfilter.lastModified() > lastModified){ synchronized(BadWord.class){ try{ lastModified = wordfilter.lastModified(); LineIterator lines = FileUtils.lineIterator(wordfilter, "utf-8"); while(lines.hasNext()){ String line = lines.nextLine(); if(StringUtils.isNotBlank(line)) words.add(StringUtils.trim(line).toLowerCase()); } }catch(IOException e){ e.printStackTrace(); } } } } /** * 檢查敏感字內容 * @param contents */ public static String check(String ...contents) { if(!wordfilter.exists()) return null; checkReload(); for(String word : words){ for(String content : contents) if(content!=null && content.indexOf(word) >= 0) return word; } return null; } /** * 檢查字符串是否包含敏感詞 * * @param content * @return */ public static boolean isContain(String content) { if(!wordfilter.exists()) return false; checkReload(); for(String word : words){ if(content!=null && content.indexOf(word) >= 0) return true; } return false; } /** * 替換掉字符串中的敏感詞 * * @param str 等待替換的字符串 * @param replaceChar 替換字符 * @return */ public static String replace(String str,String replaceChar){ checkReload(); for(String word : words){ if(str.indexOf(word)>=0){ String reChar = ""; for(int i=0;i<word.length();i++){ reChar += replaceChar; } str = str.replaceAll(word, reChar); } } return str; } public static List<String> lists() { checkReload(); return words; } /** * 添加敏感詞 * * @param word * @throws IOException */ public static void add(String word) throws IOException { word = word.toLowerCase(); if(!words.contains(word)){ words.add(word); FileUtils.writeLines(wordfilter, "UTF-8", words); lastModified = wordfilter.lastModified(); } } /** * 刪除敏感詞 * * @param word * @throws IOException */ public static void delete(String word) throws IOException { word = word.toLowerCase(); words.remove(word); FileUtils.writeLines(wordfilter, "UTF-8", words); lastModified = wordfilter.lastModified(); } public static void main(String[] args) throws Exception{ System.out.println(BadWord.replace("中國共產黨釣魚島","*")); System.out.println(BadWord.isContain("島")); BadWord.add("傻逼"); } }來自:http://blog.csdn.net/wiker_yong/article/details/16823535
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!