Java工具类


java工具类

生成不重复随机数列表

/*取1-max(max可取到)amount:需要生成的个数,max:随机生成为1-max*/
   public static List<Object> random(int amount, int max) {

       if (amount > max) { // 需要数字总数必须小于数的最大值,以免死循环!
           throw new ArrayStoreException(
                   "The amount of array element must smallar than the maximum value !");
       }
       int[] array = new int[amount];
       for (int i = 0; i < array.length; i++) {
           array[i] = -1; // 初始化数组,避免后面比对时数组内不能含有0。
       }
       Random random = new Random();
       int num;
       amount -= 1; // 数组下标比数组长度小1
       while (amount >= 0) {
           num = random.nextInt(max)+1;
           if (exist(num, array, amount - 1)) {
               continue;
           }
           array[amount] = num;
           amount--;
       }
       List<Object> collect = Arrays.stream(array).boxed().collect(Collectors.toList());
       return collect;
   }

   private static boolean exist(int num, int[] array, int need) {

       for (int i = array.length - 1; i > need; i--) {// 大于need用于减少循环次数,提高效率。
           if (num == array[i]) {
               return true;
           }
       }
       return false;
   }

md5加密

/**
    * 使用md5的算法进行加密
    */
   public static String md5(String plainText) {
       byte[] secretBytes = null;
       try {
           secretBytes = MessageDigest.getInstance("md5").digest(
                   plainText.getBytes());
       } catch (NoSuchAlgorithmException e) {
           throw new RuntimeException("没有md5这个算法!");
       }
       String md5code = new BigInteger(1, secretBytes).toString(16);// // 16进制数字
       // 如果生成数字未满32位,需要前面补0
       for (int i = 0; i < 32 - md5code.length(); i++) {
           md5code = "0" + md5code;
       }
       return md5code;
   }

检查json对象里面是否包含一些属性

/**
    * description: 检查json对象里面是否包含一些属性,并且不为null
    * @author zwq
    * @date 2021/9/26 16:27
    * @param jsonObject 检查json对象
    * @param strings 检查的属性
    * @return boolean
    */
   public static boolean jsonObjectContains(JSONObject jsonObject,String... strings){
       for(int i=0;i<strings.length;i++){
           if(!jsonObject.containsKey(strings[i])){
               return false;
           }
           if(jsonObject.get(strings[i]) == null){
               return false;
           }
       }
       return true;
   }

过滤对象属性

/**
    * description: 过滤对象属性
    * @author zwq
    * @date 2021/7/11 9:25
    * @param object 过滤对象
    * @param excludeProperties 过滤的属性(字符串数组形式)
    * @return java.lang.String 返回的是jsontext
    */
   public static String excludeProperty(Object object,String[] excludeProperties){
       /**
        * 指定排除属性过滤器和包含属性过滤器
        * 指定排除属性过滤器:转换成JSON字符串时,排除哪些属性
        * 指定包含属性过滤器:转换成JSON字符串时,包含哪些属性
        */
       for (String s:excludeProperties){
           System.out.println(s);
       }
       PropertyPreFilters filters = new PropertyPreFilters();
       PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
       excludefilter.addExcludes(excludeProperties);
       return JSONObject.toJSONString(object,excludefilter);
   }

判断字符串是否为数字

/**
    * description: 判断字符串是否为数字
    * @author zwq
    * @date 2021/9/8 22:02
    * @param str
    * @return boolean
    */
   public static boolean isNumeric(String str) {
       Pattern pattern = Pattern.compile("[0-9]*");
       Matcher isNum = pattern.matcher(str);
       if (isNum.matches()) {
           return true;
       } else {
           return false;
       }
   }

判断字符串是否为日期格式

/**
    * description: 判断字符串是否为日期格式
    * @author zwq
    * @date 2021/9/8 22:02
    * @param strDate
    * @return boolean
    */
   public static boolean isDate(String strDate) {
       Pattern pattern = Pattern
               .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
       Matcher m = pattern.matcher(strDate);
       if (m.matches()) {
           return true;
       } else {
           return false;
       }
   }

验证手机号(大陆号码)

/**
    * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
    * 此方法中前三位格式有:
    * 13+任意数
    * 145,147,149
    * 15+除4的任意数(不要写^4,这样的话字母也会被认为是正确的)
    * 166
    * 17+3,5,6,7,8
    * 18+任意数
    * 198,199
    * description: 验证大陆手机号
    * @author zwq
    * @date 2021/9/8 22:04
    * @param str
    * @return boolean
    */
   public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
       // ^ 匹配输入字符串开始的位置
       // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d
       // $ 匹配输入字符串结尾的位置
       String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
               "|(18[0-9])|(19[8,9]))\\d{8}$";
       Pattern p = Pattern.compile(regExp);
       Matcher m = p.matcher(str);
       return m.matches();
   }

验证手机号(香港)

/**
    * 香港手机号码8位数,5|6|8|9开头+7位任意数
    * description: 验证香港手机号
    * @author zwq
    * @date 2021/9/8 22:05
    * @param str
    * @return boolean
    */
   public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
       // ^ 匹配输入字符串开始的位置
       // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d
       // $ 匹配输入字符串结尾的位置
       String regExp = "^(5|6|8|9)\\d{7}$";
       Pattern p = Pattern.compile(regExp);
       Matcher m = p.matcher(str);
       return m.matches();
   }

验证身份证

/**
    * description: 身份证有效验证
    * @author zwq
    * @date 2021/9/8 21:59
    * @param IDStr 身份证号
    * @return boolean
    */
   public static boolean IDCardValidate(String IDStr) throws ParseException {
       String[] ValCodeArr = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
       String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2" };
       String Ai = "";
       // ================ 号码的长度18位 ================
       if (IDStr.length() != 18) {
           return false;
       }
       // ================ 数字 除最后以为都为数字 ================
       if (IDStr.length() == 18) {
           Ai = IDStr.substring(0, 17);
       }
       if (isNumeric(Ai) == false) {
           //errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。";
           return false;
       }
       // ================ 出生年月是否有效 ================
       String strYear = Ai.substring(6, 10);// 年份
       String strMonth = Ai.substring(10, 12);// 月份
       String strDay = Ai.substring(12, 14);// 日
       if (isDate(strYear + "-" + strMonth + "-" + strDay) == false) {
	//errorInfo = "身份证生日无效。";
           return false;
       }
       GregorianCalendar gc = new GregorianCalendar();
       SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
       try {
           if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150 || (gc.getTime().getTime() - s.parse(strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
               //errorInfo = "身份证生日不在有效范围。";
               return false;
           }
       } catch (NumberFormatException e) {
           e.printStackTrace();
       } catch (java.text.ParseException e) {
           e.printStackTrace();
       }
       if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
           //errorInfo = "身份证月份无效";
           return false;
       }
       if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
           //errorInfo = "身份证日期无效";
           return false;
       }
       // ================ 地区码时候有效 ================
       Hashtable h = GetAreaCode();
       if (h.get(Ai.substring(0, 2)) == null) {
           //errorInfo = "身份证地区编码错误。";
           return false;
       }
       // ================ 判断最后一位的值 ================
       int TotalmulAiWi = 0;
       for (int i = 0; i < 17; i++) {
           TotalmulAiWi = TotalmulAiWi + Integer.parseInt(String.valueOf(Ai.charAt(i))) * Integer.parseInt(Wi[i]);
       }
       int modValue = TotalmulAiWi % 11;
       String strVerifyCode = ValCodeArr[modValue];
       Ai = Ai + strVerifyCode;
       if (IDStr.length() == 18) {
           if (Ai.equals(IDStr) == false) {
               //errorInfo = "身份证无效,不是合法的身份证号码";
               return false;
           }
       } else {
           return true;
       }
       return true;
   }

验证邮箱

/**
 * 验证邮箱
 *
 * @param email
 * @return
 */
public static boolean checkEmail(String email) {
	String regex = "^\\w+[-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$ ";
	return check(email, regex);
}

list去重

	/**
     * description: list去重
     * @author zwq
     * @date 2021/10/1 23:51
     * @param list
     * @return java.util.List
     */
    public static List removeDuplicationByHashSet(List<Integer> list) {
        HashSet set = new HashSet(list);
        //把List集合所有元素清空
        list.clear();
        //把HashSet对象添加至List集合
        list.addAll(set);
        return list;
        }
}

json转换工具

import java.util.List;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
 
/**
 * json转换工具类
 */
public class JsonUtils {
 
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();
 
    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
}

cookie的读写

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
 
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
 
/**
 * 
 * Cookie 工具类
 *
 */
public final class CookieUtils {
 
    /**
     * 得到Cookie的值, 不编码
     * 
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        return getCookieValue(request, cookieName, false);
    }
 
    /**
     * 得到Cookie的值,
     * 
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    if (isDecoder) {
                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                    } else {
                        retValue = cookieList[i].getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }
 
    /**
     * 得到Cookie的值,
     * 
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
        	 e.printStackTrace();
        }
        return retValue;
    }
 
    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue) {
        setCookie(request, response, cookieName, cookieValue, -1);
    }
 
    /**
     * 设置Cookie的值 在指定时间内生效,但不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue, int cookieMaxage) {
        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
    }
 
    /**
     * 设置Cookie的值 不设置生效时间,但编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue, boolean isEncode) {
        setCookie(request, response, cookieName, cookieValue, -1, isEncode);
    }
 
    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue, int cookieMaxage, boolean isEncode) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
    }
 
    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue, int cookieMaxage, String encodeString) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
    }
 
    /**
     * 删除Cookie带cookie域名
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
            String cookieName) {
        doSetCookie(request, response, cookieName, "", -1, false);
    }
 
    /**
     * 设置Cookie的值,并使其在指定时间内生效
     * 
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
            String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request) {// 设置域名的cookie
            	String domainName = getDomainName(request);
            	System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                	cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
        	 e.printStackTrace();
        }
    }
 
    /**
     * 设置Cookie的值,并使其在指定时间内生效
     * 
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
            String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else {
                cookieValue = URLEncoder.encode(cookieValue, encodeString);
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request) {// 设置域名的cookie
            	String domainName = getDomainName(request);
            	System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                	cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
        	 e.printStackTrace();
        }
    }
 
    /**
     * 得到cookie的域名
     */
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;
 
        String serverName = request.getRequestURL().toString();
        if (serverName == null || serverName.equals("")) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            serverName = serverName.substring(7);
            final int end = serverName.indexOf("/");
            serverName = serverName.substring(0, end);
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                domainName = "." + domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }
 
        if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        return domainName;
    }
 
}

获取异常的堆栈信息

import java.io.PrintWriter;
import java.io.StringWriter;
 
public class ExceptionUtil {
 
	/**
	 * 获取异常的堆栈信息
	 * 
	 * @param t
	 * @return
	 */
	public static String getStackTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
 
		try {
			t.printStackTrace(pw);
			return sw.toString();
		} finally {
			pw.close();
		}
	}
}

各种id生成策略

import java.util.Random;
 
/**
 * 各种id生成策略
 * <p>Title: IDUtils</p>
 * <p>Description: </p>
 * @date	2015年7月22日下午2:32:10
 * @version 1.0
 */
public class IDUtils {
 
	/**
	 * 图片名生成
	 */
	public static String genImageName() {
		//取当前时间的长整形值包含毫秒
		long millis = System.currentTimeMillis();
		//long millis = System.nanoTime();
		//加上三位随机数
		Random random = new Random();
		int end3 = random.nextInt(999);
		//如果不足三位前面补0
		String str = millis + String.format("%03d", end3);
		
		return str;
	}
	
	/**
	 * 商品id生成
	 */
	public static long genItemId() {
		//取当前时间的长整形值包含毫秒
		long millis = System.currentTimeMillis();
		//long millis = System.nanoTime();
		//加上两位随机数
		Random random = new Random();
		int end2 = random.nextInt(99);
		//如果不足两位前面补0
		String str = millis + String.format("%02d", end2);
		long id = new Long(str);
		return id;
	}
	
	public static void main(String[] args) {
		for(int i=0;i< 100;i++)
		System.out.println(genItemId());
	}
}

  目录