屏蔽字工具类 Java读取Excel工具类 读取到内存中

MaskWordTable: 屏蔽字工具类

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import Common.FunctionHelper;
import Common.Container.CCMap;

public class MaskWordTable
{
	private final static String FILENAME = "MaskWord.xls";
	private final static String PATH = Thread.currentThread().getContextClassLoader().getResource(FILENAME).getPath();
	
	private CCMap<String, List<String>> mMaskWordTable = new CCMap<String, List<String>>();
	
	private MaskWordTable()
	{
		
	}
	
	private static class LazyHolder
	{
		private final static MaskWordTable INSTANCE = new MaskWordTable();
	}
	
	public final static MaskWordTable getMaskWordTable()
	{
		return LazyHolder.INSTANCE;
	}
	
	/**
	 * @see read excel
	 */
	private boolean ReadExcel()
	{
		try
		{
			List<String> table = ExcelUtil.exportListFromExcel(PATH, FILENAME);
			for(String row : table)
			{
				AddRow(row);
			}
			Sort();
			return true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * @see 是否包含屏蔽字
	 */
	public boolean IsHave(String text)
	{
		if(0 == mMaskWordTable.Size())
		{
			ReadExcel();
		}
		if(FunctionHelper.StringIsNullOrEmpty(text))
		{
			return false;
		}
		for(int i = 0; i < text.length(); ++i)
		{
			String key = text.substring(i, i + 1);
			String content = text.substring(i);
			List<String> value = mMaskWordTable.GetValue(key);
			if(null == value)
			{
				continue;
			}
			for(String word : value)
			{
				if(content.indexOf(word) >= 0)
				{
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * @see 屏蔽字转换
	 */
	public String ConvertTo(String text)
	{
		if(0 == mMaskWordTable.Size())
		{
			ReadExcel();
		}
		if(FunctionHelper.StringIsNullOrEmpty(text))
		{
			return "";
		}
		List<String> sensitiveWords = new LinkedList<String>();
		for(int i = 0; i < text.length(); ++i)
		{
			String key = text.substring(i, i + 1);
			String content = text.substring(i);
			List<String> value = mMaskWordTable.GetValue(key);
			if(null == value)
			{
				continue;
			}
			for(String word : value)
			{
				if(content.indexOf(word) >= 0)
				{
					i += word.length() - 1;
					sensitiveWords.add(word);
				}
			}
		}
		for(String sensitiveWord : sensitiveWords)
		{
			text = text.replaceFirst(sensitiveWord, StarGenerator(sensitiveWord.length()));
		}
		return text;
	}
	
	private String StarGenerator(int length)
	{
		String stars = "";
		for(int i = 0; i < length; ++i)
		{
			stars += "*";
		}
		return stars;
	}
	
	private class LengthComparator implements Comparator<String>
	{
		@Override
		public int compare(String o1, String o2)
		{
			return o2.length() - o1.length();
		}
	}
	
	private void Sort()
	{
		List<List<String>> values = mMaskWordTable.GetValues();
		for(List<String> value : values)
		{
			Collections.sort(value, new LengthComparator());
		}
	}
	
	private void AddRow(String row)
	{
		if(FunctionHelper.StringIsNullOrEmpty(row))
		{
			return;
		}
		String key = row.substring(0, 1);
		List<String> value = mMaskWordTable.GetValue(key);
		if(null != value)
		{
			value.add(row);
		}
		else
		{
			value = new LinkedList<String>();
			value.add(row);
			mMaskWordTable.Put(key, value);
		}
	}
}

ExcelUtil: Java读取Excel工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {
	
	private final static String XLS = "xls";//Excel 2003
	private final static String XLSX = "xlsx";//Excel 2007

	/**
	 * Excel文件的Sheet导出至List
	 * 
	 * @param file
	 * @param sheetNum
	 * @return
	 */
	public static List<String> parseListExcel(String path, String fileName) {
		List<String> list = new ArrayList<String>();
		try {
			FileInputStream in = new FileInputStream(new File(path));
			Workbook workbook = null;
			try {
				workbook = getWorkbook(in, fileName);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("文件后缀解析失败");
			}
			Sheet sheet = workbook.getSheetAt(0);//读取第一个工作表
			// 解析公式结果
			FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
			int minRowIx = sheet.getFirstRowNum();
			int maxRowIx = sheet.getLastRowNum();
			for (int rowIx = minRowIx; rowIx <= maxRowIx; rowIx++) {
				Row row = sheet.getRow(rowIx);
				StringBuilder sb = new StringBuilder();
				short minColIx = row.getFirstCellNum();
				short maxColIx = row.getLastCellNum();
				for (short colIx = minColIx; colIx <= maxColIx; colIx++) {
					Cell cell = row.getCell(new Integer(colIx));
					CellValue cellValue = evaluator.evaluate(cell);
					if (cellValue == null) {
						continue;
					}
					sb.append(getCellValue(cell));
				}
				list.add(sb.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 *  Excel文件的Sheet导出至List<Map>
	 *  
	 * @param path 文件路径
	 * @param fileName 文件名
	 * @param mapping
	 * @return
	 */
	public static List<Map<String, Object>> parseMapExcel(String path, String fileName, Map<String, String> mapping){
		// 返回数据
		List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();
		try {
			// 根据文件名来创建Excel工作薄
			FileInputStream in = new FileInputStream(new File(path));
			Workbook work = getWorkbook(in, fileName);
			if (null == work) {
				throw new Exception("创建Excel工作薄为空!");
			}
			Sheet sheet = null;
			Row row = null;
			Cell cell = null;
			
			// 遍历Excel中所有的sheet
			for (int i = 0; i < work.getNumberOfSheets(); i++) {
				sheet = work.getSheetAt(i);
				if (sheet == null)
					continue;
				// 取第一行标题
				row = sheet.getRow(0);
				String title[] = null;
				if (row != null) {
					title = new String[row.getLastCellNum()];
					for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
						cell = row.getCell(y);
						title[y] = (String) getCellValue(cell);
					}
				} else
					continue;
				// 遍历当前sheet中的所有行
				for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
					row = sheet.getRow(j);
					Map<String, Object> m = new HashMap<String, Object>();
					// 遍历所有的列
					for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
						cell = row.getCell(y);
						String key = title[y];
						m.put(mapping.get(key), getCellValue(cell));
					}
					ls.add(m);
				}
			}
			work.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ls;
	}

	/**
	 * @see 根据文件后缀,自适应上传文件的版本
	 */
	private static Workbook getWorkbook(InputStream in, String fileName) throws Exception {
		Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
        if (XLS.equals(fileType)) {
            wb = new HSSFWorkbook(in); // 2003-
        } else if (XLSX.equals(fileType)) {
            wb = new XSSFWorkbook(in); // 2007+
        } else {
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
	}

	/**
	 * @see 对表格中数值进行格式化
	 */
	private static Object getCellValue(Cell cell) {
		Object value = "";
		if(cell == null){
			return value;
		}
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			value = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_NUMERIC:
		case Cell.CELL_TYPE_BOOLEAN:
		case Cell.CELL_TYPE_FORMULA:
		case Cell.CELL_TYPE_BLANK:
			cell.setCellType(Cell.CELL_TYPE_STRING);
			value = cell.getStringCellValue();
			break ;
		default:
			break;
		}
		return value;
	}
}

Test: 测试

public class Test {
	public static void main(String[] args) {
		String str = "xxxxx";
		String result = MaskWordTable.getMaskWordTable().IsHave(str) ? MaskWordTable.getMaskWordTable().ConvertTo(str) : str;
		System.out.println(result);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值