常用的StringUtil工具类

常用的工具类

// StringUtil工具类
public class StringUtil {

    //object转字符串
    public static String toString(Object object){
        return object == null ? "" : object.toString();
    }
    
    //object转字符串给一个默认值
    public static String toString(Object object,String defaultValue){
        return object == null ? defaultValue : object.toString();
    }
    
    //object转int给默认值
    public static int toInt(Object obj,int defaultValue) {
        try {
            return Integer.valueOf(obj.toString());
        } catch (Exception e){
            return defaultValue;
        }
    }
    
    //object转double给默认值
    public static double toDouble(Object obj,double defaultValue){
    	try {
			return Double.valueOf(obj.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return defaultValue;
		}
    }
    
	//判断obj是否为空
    public static boolean isNotEmpty(Object obj) {
        return obj != null && !"".equals(obj.toString().trim());
    }
    
    //生成32位的UUID
    public static String getUUID32() {
        return UUID.randomUUID().toString().replace("-", "");
    }
    
    /**
     * 判断一个字符串是否有值,空格也不算有值
     * @param str 字符串
     * @return boolean
     */
    public static boolean availableStr(String str){
        if(str != null && !"".equals(str) && !"".equals(str.trim())){
            return true;
        }else{
            return false;
        }
    }
    
    /**
     * 验证文件名是否正确
     * @param param 文件名
     * @return 正确返回true
     */
    public static boolean verifyFileName(String param) {
        if (param == null || "".equals(param)||param.length()>255) {
            return false;
        }
        if (param.indexOf("..")>-1||param.indexOf("//")>-1||param.indexOf("")>-1){
            return false;
        }
        String regEx = "[^*|\\:\"<>?]+\\.[^*|\\:\"<>?\u4E00-\u9FA5]+";
        return param.matches(regEx);
    }
    
    /**
     * 验证文件路径是否正确
     * @param param 文件路径
     * @return 正确返回true
     */
    public static boolean verifyFilePath(String param) {
        if (param == null || "".equals(param)||param.length()>255) {
            return false;
        }
        if (param.indexOf("..")>-1||param.indexOf("//")>-1||param.indexOf("")>-1){
            return false;
        }
        String regEx = "[^*|\"<>?\\.\u4E00-\u9FA5]+";
        return param.matches(regEx);
    }
    
    /**
     * 处理文件路径
     * @param path 文件路径
     * @return 处理过的文件路径
     */
    public static String filePathFilter(String path){
        if (path == null) return null;
        String cleanString = "";
        for (int i = 0; i < path.length(); ++i) {
            cleanString += cleanChar(path.charAt(i));
        }
        if (cleanString.indexOf("..")>0||cleanString.indexOf("//")>0||cleanString.indexOf("\\\\")>0||
                cleanString.indexOf("https")>0||cleanString.indexOf("http")>0){
            cleanString = "error.jpg";
        }
        if (cleanString.indexOf("\\")>-1){
            cleanString = cleanString.replaceAll("\\\\",Matcher.quoteReplacement(File.separator));
        }
        if (cleanString.indexOf("/")>-1){
            cleanString = cleanString.replaceAll("/",Matcher.quoteReplacement(File.separator));
        }
        return cleanString;
    }
    
    /**
     * 输入输出处理
     * @param input 输入输出字符
     * @return 处理后结果
     */
    public static String filterInput(String input) {
        List<String> list = new ArrayList<String>();

        list.add("<");
        list.add(">");
        list.add("(");
        list.add(")");
        list.add("&");
        list.add("?");
        list.add(";");

        String encode = Normalizer.normalize(input, Normalizer.Form.NFKC);

        for (int i=0;i<list.size();i++) {
            encode = encode.replace(list.get(i), "");
        }

        return encode;
    }

    /**
     * 过滤字符串的特殊字符
     * @param str 要过滤的字符串
     * @return 过滤后的字符串
     */
    public static String filterStr(String str){
        String resValue = scriptPattern.matcher(str).replaceAll("");
        resValue = singleScriptPattern.matcher(resValue).replaceAll("");
        resValue = singleScriptPattern2.matcher(resValue).replaceAll("");
        resValue = evalScriptPattern.matcher(resValue).replaceAll("");
        resValue = onloadScriptPattern.matcher(resValue).replaceAll("");
        resValue = onmousScriptPattern.matcher(resValue).replaceAll("");
        resValue = alertScriptPattern.matcher(resValue).replaceAll("");
        resValue = iframeScriptPattern.matcher(resValue).replaceAll("");
        resValue = aTagPattern.matcher(resValue).replaceAll("");
        resValue = otherScriptPattern.matcher(resValue).replaceAll("");
        resValue = fontfamilyPattern.matcher(resValue).replaceAll("");
        Pattern pa = Pattern.compile("[`~!@$%^&*()\\+\\=\\{}|:\"?><【】\\/\\r\\n]");//[`~!@$%^&*()\+\=\{}|:"?><【】\/r\/n]
        Matcher ma = pa.matcher(resValue);
        if(ma.find()){
            resValue = ma.replaceAll("");
        }
        return resValue;
    }

    /**
     * 过滤Map的value值
     * @param param 要过滤的map
     * @return 过滤结果
     */
    public static Map<String,String> filterMapValue(Map<String,String> param){
        Map<String,String> res = new HashMap<>();
        for (String key:param.keySet()){
            String value = StringUtil.toString(param.get(key));
            value = filterStr(value);
            res.put(key,value);
        }
        return res;
    }

    /**
     * 过滤map的value值
     * @param param 要过滤的map
     * @return 过滤结果
     */
    public static Map<String,Object> filterMapValueObject(Map<String,Object> param){
        Map<String,Object> res = new HashMap<>();
        for (String key:param.keySet()){
            if (param.get(key) instanceof String){
                String value = StringUtil.toString(param.get(key));
                value = filterStr(value);
                res.put(key,value);
            }else {
                res.put(key,param.get(key));
            }
        }
        return res;
    }

    /**
     * 过滤Map的list集合中的字符串
     * @param param 要过滤的map集合
     * @return 过滤结果
     */
    public static List<Map<String,String>> filterListMap(List<Map<String,String>> param){
        if (param!=null&&param.size()>=1){
            List<Map<String,String>> res = new ArrayList<>();
            for (int i = 0;i<param.size();i++){
                Map<String,String> map = filterMapValue(param.get(i));
                res.add(map);
            }
            return res;
        }
        return param;
    }
    /**
     * 过滤List<entity>list实体类中的字符串
     * @param param 实体类list集合
     * @throws Exception
     */
    public static void filterListObject(List param) throws Exception{
        if (param != null&&param.size()>=1){
            for (int i = 0; i < param.size();i++){
                Field[] fields = param.get(i).getClass().getDeclaredFields();
                for (int j = 0;j<fields.length;j++){
                    // 将属性的首字母大写
                    String name = fields[j].getName().replaceFirst(fields[j].getName().substring(0, 1)
                            , fields[j].getName().substring(0, 1).toUpperCase());
                    // 获取属性类型
                    String type = fields[j].getGenericType().toString();
                    if (type.equals("class java.lang.String")){
                        // 如果type是类类型,则前面包含"class ",后面跟类名
                        //该属性有对应的getter和setter方法
                        Method[] methods = param.get(i).getClass().getMethods();//改类的所有public方法
                        if (hasMethod(methods,"get"+name)&&hasMethod(methods,"set"+name)){
                            Method m = param.get(i).getClass().getMethod("get" + name);
                            // 调用getter方法获取属性值
                            String value = (String) m.invoke(param.get(i));
                            //调用setter方法赋属性值
                            if (value != null) {
                                m = param.get(i).getClass().getMethod("set" + name, String.class);
                                m.invoke(param.get(i), filterStr(value));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 判断数组中是否有对应方法名的方法
     * @param methods 方法数组
     * @param name 方法名
     * @return
     */
    private static boolean hasMethod(Method[] methods,String name){
        if (methods==null||methods.length==0){
            return false;
        }
        for (int i =0; i < methods.length;i++){
            if (methods[i].getName().equals(name)){
                return true;
            }
        }
        return false;
    }

    /**
     * 过滤字符串数组中的特殊字符
     * @param param 要过滤的字符串数组
     * @return 过滤的结果
     */
    public static String[] filterStrArr(String[] param){
        if (param == null){
            return null;
        }
        if (param.length >0){
            for (int i =0;i < param.length;i++){
                param[i] = filterStr(param[i]);
            }
        }
        return param;
    }

    /**
     * 过滤字符串集合中的特殊字符
     * @param param 要过滤的特殊字符串
     * @return 过滤的结果
     */
    public static List<String> filterStrList(List<String> param){
        if (param==null||param.size()==0){
            return param;
        }
        List<String> res = new ArrayList<>();
        for (int i =0;i<(param.size()>MAX_RESULT_SIZE?MAX_RESULT_SIZE:param.size());i++){
            res.add(filterStr(param.get(i)));
        }
        return res;
    }

    /**
     * 判断一个字符在字符串中出现的次数
     * @param str 字符串
     * @param ch 字符
     * @return
     */
    public static int getCharNumber(String str,String ch){
        if (str == null || str.length()==0 || ch.indexOf(ch)<0){
            return -1;
        }
        int count = 0;
        int index = 0;
        do{
            index = str.indexOf(ch,index);
            if (index>-1){
                count++;
                index = index+ch.length();
            }
        }while (index>-1);
        return count;
    }


}

猜你喜欢

转载自blog.csdn.net/qq_45593609/article/details/105427407