Java字符串脱敏工具类

首先引入依赖


    commons-io
    commons-io
    2.2


    org.apache.commons
    commons-lang3
    3.0

敏感字段文件:wordfilter.txt

共产党

 Java工具类:

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.lang3.StringUtils;
 
/**
 * 
  * ClassName: 敏感字段处理工具类 
* Function: TODO ADD FUNCTION.
* Reason: TODO ADD REASON(可选).
* date: 2018年5月18日 下午16:02:37
* * @author huangSir * @version * @since JDK 1.6 */ public class SensitiveWordUtils { private final static File wordfilter = new File("C:/wordfilter.txt"); private static List words = new ArrayList(); static { synchronized(SensitiveWordUtils.class){ try{ LineIterator lines = FileUtils.lineIterator(wordfilter, "utf-8"); boolean flag = false; while(lines.hasNext()){ String line = lines.nextLine(); if(!flag){ if(line.length()>1){ line=line.substring(1); } flag = true; } 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; } 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; for(String word : words){ if(content!=null && content.indexOf(word) >= 0) return true; } return false; } /** * 字符串中的敏感词用*替换 * * @param str * @return */ public static String desensitization(String str){ for(String word : words){ if(str.indexOf(word)>=0){ String reChar = ""; for(int i=0;i getSensitiveWords() { return words; } /** * 添加敏感词 * * @param word * @throws IOException */ public static void addSensitiveWord(String word) throws IOException { word = word.toLowerCase(); if(!words.contains(word)){ words.add(word); FileUtils.writeLines(wordfilter, "UTF-8", words); } } /** * 删除敏感词 * * @param word * @throws IOException */ public static void deleteSensitiveWord(String word) throws IOException { word = word.toLowerCase(); if(words.contains(word)){ words.remove(word); FileUtils.writeLines(wordfilter, "UTF-8", words); } } public static void main(String[] args) throws Exception{ System.out.println(desensitization("中国共产党万岁"));; } }

运行结果:

你可能感兴趣的:(常用工具,字符串脱敏)