java开发常用工具类集合总结

小灰灰 2021-04-19 14:54 689阅读 0赞

如果想学习Java工程化、高性能及分布式、深入浅出。性能调优、Spring,MyBatis,Netty源码分析的朋友可以加我的Java高级程序员群:180705916,群里有阿里大牛直播讲解技术,以及Java大型互联网技术的视频免费分享给大家。

1)java正则表达式的匹配包括:邮箱,手机,姓名,昵称,身份证号,银行卡号等;

2)生成6位随机数;

3)对url中字符串进行编码和解码

4)获取客户端ip地址

5)获取系统当前时间

6)生成32位编码不含横线

7)生成MD5编码

8)通过身份证获取性别

9)通过身份证获取生日

10)通过身份证获取生日

11)手机号中间4位替换成星号

12)邮箱地址加星号

13)生成随机密码

下面给出使用方法类;

  1. package commons;
  2. import com.alibaba.fastjson.JSONObject; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.PropertyUtilsBean; import org.springframework.util.DigestUtils; import org.springframework.util.StringUtils;
  3. import javax.servlet.http.HttpServletRequest; import [java.io][].*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.security.SecureRandom; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream;
  4. /**
  5. * 通用工具类. */ public class CommonUtil { private static SecureRandom random = new SecureRandom();
  6. public static final Pattern MAIL_PATTERN = Pattern.compile("^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$");
  7. public static final Pattern MOBILE_PATTERN = Pattern.compile("^1[3|4|5|7|8][0-9]d{8}$");
  8. public static final Pattern NAME_PATTERN = Pattern.compile("^[u4E00-u9FBF][u4E00-u9FBF(.|·)]{0,13}[u4E00-u9FBF]$");
  9. public static final Pattern NICKNAME_PATTERN = Pattern.compile("^((?!d{5})[u4E00-u9FBF(.|·)|0-9A-Za-z_]){2,11}$");
  10. public static final Pattern PASSWORD_PATTERN = Pattern.compile("^[sS]{6,30}$");
  11. public static final Pattern CODE_PATTERN = Pattern.compile("^0d{2,4}$");
  12. public static final Pattern POSTCODE_PATTERN = Pattern.compile("^d{6}$");
  13. public static final Pattern ID_PATTERN = Pattern.compile("^d{6}(d{8}|d{11})[0-9a-zA-Z]$");
  14. public static final Pattern BANK_CARD_PATTERN = Pattern.compile("^d{16,30}$");
  15. /**
  16. * 生成6位随机数字, 用于手机短信验证码.
  17. *
  18. * @return 6位随机数字 */ public static int random() { int x = Math.abs(random.nextInt(899999));
  19. return x + 100000; }
  20. /**
  21. * 对url字符串进行编码.
  22. *
  23. * @param url 要编码的url字符串
  24. * @return 编码后的字符串 */ public static String urlEncoder(String url) { if (StringUtils.isEmpty(url)) { return null; } try { return java.net.URLEncoder.encode(url, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
  25. /**
  26. * 对url字符串进行解码.
  27. *
  28. * @param url 要解码的url字符串
  29. * @return 解码后的字符串 */ public static String urlDecoder(String url) { if (StringUtils.isEmpty(url)) { return null; } try { return URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
  30. /**
  31. * 验证字符串是不是邮箱.
  32. *
  33. * @param email 要验证的邮箱
  34. * @return 是否正确邮箱 */ public static boolean validateEmail(String email) { if (StringUtils.isEmpty(email)) { return false; } Matcher m = MAIL_PATTERN.matcher(email); return m.matches(); }
  35. /**
  36. * 验证字符串是不是手机号.
  37. *
  38. * @param mobile 要验证的手机号
  39. * @return 是否正确手机号 */ public static boolean validateMobile(String mobile) { if (StringUtils.isEmpty(mobile)) { return false; } Matcher m = MOBILE_PATTERN.matcher(mobile); return m.matches(); }
  40. /**
  41. * 验证身份证是否有效.
  42. *
  43. * @param idCardNumber 要验证的身份证
  44. * @return 是否正确身份证 */ public static boolean validateId(String idCardNumber) { if (StringUtils.isEmpty(idCardNumber)) { return false; } Matcher m = ID_PATTERN.matcher(idCardNumber); return m.matches() && IdCardUtils.validateCard(idCardNumber); }
  45. /**
  46. * 验证姓名是否有效.
  47. *
  48. * @param name 要验证的姓名
  49. * @return 是否正确姓名 */ public static boolean validateName(String name) { if (StringUtils.isEmpty(name) || name.replaceAll("[^.·]", "").length() > 1) { return false; } Matcher m = NAME_PATTERN.matcher(name); return m.matches(); }
  50. /**
  51. * 验证昵称是否有效.
  52. *
  53. * @param nickname 要验证的昵称
  54. * @return 是否正确昵称 */ public static boolean validateNickname(String nickname) {
  55. //规则 不能包含5个数字 允许中英文和数字 2-11位 if (StringUtils.isEmpty(nickname) || nickname.replaceAll("[^0-9]", "").length() > 4) { return false; } Matcher m = NICKNAME_PATTERN.matcher(nickname); return m.matches(); }
  56. /**
  57. * 验证密码格式是否有效.
  58. *
  59. * @param password 要验证的密码
  60. * @return 是否正确密码格式 */ public static boolean validatePassword(String password) { if (StringUtils.isEmpty(password)) { return false; } Matcher m = PASSWORD_PATTERN.matcher(password); return m.matches(); }
  61. /**
  62. * 验证区号是否有效.
  63. *
  64. * @param code 要验证的区号
  65. * @return 是否正确身份证 */ public static boolean validateCode(String code) { if (StringUtils.isEmpty(code)) { return false; } Matcher m = CODE_PATTERN.matcher(code); return m.matches(); }
  66. /**
  67. * 验证邮政编码是否有效.
  68. *
  69. * @param postcode 要验证的邮政编码
  70. * @return 是否正确邮政编码 */ public static boolean validatePostcode(String postcode) { if (StringUtils.isEmpty(postcode)) { return false; } Matcher m = POSTCODE_PATTERN.matcher(postcode); return m.matches(); }
  71. /**
  72. * 验证银行卡是否有效.
  73. *
  74. * @param bankCardNumber 要验证的银行卡号
  75. * @return 是否正确银行卡号 */ public static boolean validateBankCardNumber(String bankCardNumber) { if (StringUtils.isEmpty(bankCardNumber)) { return false; } Matcher m = BANK_CARD_PATTERN.matcher(bankCardNumber); return m.matches(); }
  76. /**
  77. * 获取客户端IP地址.
  78. *
  79. * @param request request请求
  80. * @return ip地址 */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("Cdn-Src-Ip"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if (StringUtils.hasText(ip)) { return StringUtils.tokenizeToStringArray(ip, ",")[0]; } return ""; }
  81. /**
  82. * 获取当前系统时间,以java.sql.Timestamp类型返回.
  83. *
  84. * @return 当前时间 */ public static Timestamp getTimestamp() { Timestamp d = new Timestamp(System.currentTimeMillis()); return d; }
  85. /**
  86. * 生成32位编码,不含横线
  87. *
  88. * @return uuid串 */ public static String getUUID() { String uuid = UUID.randomUUID().toString().trim().replaceAll("-", ""); return uuid.toUpperCase(); }
  89. /**
  90. * 生成MD5编码
  91. *
  92. * @param data 要编码的字符串
  93. * @return 加密后的字符串 */ public static String md5(String data) { return md5(data, 1); }
  94. /**
  95. * 生成MD5编码
  96. *
  97. * @param data 要编码的字符串
  98. * @param time 加密次数
  99. * @return 加密后的字符串 */ public static String md5(String data, int time) { byte[] bytes = data == null ? new byte[0] : data.getBytes(Constants.UTF8);
  100. while (time-- > 1) { bytes = DigestUtils.md5Digest(bytes); }
  101. return DigestUtils.md5DigestAsHex(bytes).toUpperCase(); }
  102. /**
  103. * 空字符串转为null
  104. *
  105. * @param object 要规则化的对象
  106. * @param 对象类型
  107. * @return 规则化后的对象 */ public static T normalizeBlankStringFields(T object) { if (object == null) return null;
  108. PropertyUtilsBean utils = BeanUtilsBean.getInstance().getPropertyUtils(); Stream.of(utils.getPropertyDescriptors(object)).forEach(pd -> { try { Object value = utils.getNestedProperty(object, pd.getName()); if (value == null) return;
  109. if (!StringUtils.hasText(value.toString())) {
  110. utils.setNestedProperty(object, pd.getName(), null);
  111. }
  112. } catch (Throwable e) {
  113. }
  114. 复制代码
  115. });
  116. return object; }
  117. /**
  118. * 通过身份证获取性别
  119. *
  120. * @param idNumber 身份证号
  121. * @return 返回性别, 0 保密 , 1 男 2 女 */ public static Integer getGenderByIdNumber(String idNumber) {
  122. int gender = 0;
  123. if (idNumber.length() == 15) { gender = Integer.parseInt(String.valueOf(idNumber.charAt(14))) % 2 == 0 ? 2 : 1; } else if (idNumber.length() == 18) { gender = Integer.parseInt(String.valueOf(idNumber.charAt(16))) % 2 == 0 ? 2 : 1; }
  124. return gender;
  125. }
  126. /**
  127. * 通过身份证获取生日
  128. *
  129. * @param idNumber 身份证号
  130. * @return 返回生日, 格式为 yyyy-MM-dd 的字符串 */ public static String getBirthdayByIdNumber(String idNumber) {
  131. String birthday = "";
  132. if (idNumber.length() == 15) { birthday = "19" + idNumber.substring(6, 8) + "-" + idNumber.substring(8, 10) + "-" + idNumber.substring(10, 12); } else if (idNumber.length() == 18) { birthday = idNumber.substring(6, 10) + "-" + idNumber.substring(10, 12) + "-" + idNumber.substring(12, 14); }
  133. return birthday;
  134. }
  135. /**
  136. * 通过身份证获取年龄
  137. *
  138. * @param idNumber 身份证号
  139. * @return 返回年龄 */ public static Integer getAgeByIdNumber(String idNumber) {
  140. String birthString = getBirthdayByIdNumber(idNumber); if (StringUtils.isEmpty(birthString)) { return 0; }
  141. return getAgeByBirthString(birthString);
  142. }
  143. /**
  144. * 通过身份证获取年龄
  145. *
  146. * @param idNumber 身份证号
  147. * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  148. * @return 返回年龄 */ public static Integer getAgeByIdNumber(String idNumber, boolean isNominalAge) {
  149. String birthString = getBirthdayByIdNumber(idNumber); if (StringUtils.isEmpty(birthString)) { return 0; }
  150. return getAgeByBirthString(birthString, isNominalAge);
  151. }
  152. /**
  153. * 通过生日日期获取年龄
  154. *
  155. * @param birthDate 生日日期
  156. * @return 返回年龄 */ public static Integer getAgeByBirthDate(Date birthDate) {
  157. return getAgeByBirthString(new SimpleDateFormat("yyyy-MM-dd").format(birthDate));
  158. }
  159. /**
  160. * 通过生日字符串获取年龄
  161. *
  162. * @param birthString 生日字符串
  163. * @return 返回年龄 */ public static Integer getAgeByBirthString(String birthString) {
  164. return getAgeByBirthString(birthString, "yyyy-MM-dd");
  165. }
  166. /**
  167. * 通过生日字符串获取年龄
  168. *
  169. * @param birthString 生日字符串
  170. * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  171. * @return 返回年龄 */ public static Integer getAgeByBirthString(String birthString, boolean isNominalAge) {
  172. return getAgeByBirthString(birthString, "yyyy-MM-dd", isNominalAge);
  173. }
  174. /**
  175. * 通过生日字符串获取年龄
  176. *
  177. * @param birthString 生日字符串
  178. * @param format 日期字符串格式,为空则默认"yyyy-MM-dd"
  179. * @return 返回年龄 */ public static Integer getAgeByBirthString(String birthString, String format) { return getAgeByBirthString(birthString, "yyyy-MM-dd", false); }
  180. /**
  181. * 通过生日字符串获取年龄
  182. *
  183. * @param birthString 生日字符串
  184. * @param format 日期字符串格式,为空则默认"yyyy-MM-dd"
  185. * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  186. * @return 返回年龄 */ public static Integer getAgeByBirthString(String birthString, String format, boolean isNominalAge) {
  187. int age = 0;
  188. if (StringUtils.isEmpty(birthString)) { return age; }
  189. if (StringUtils.isEmpty(format)) { format = "yyyy-MM-dd"; }
  190. try {
  191. Calendar birthday = Calendar.getInstance();
  192. Calendar today = Calendar.getInstance();
  193. SimpleDateFormat sdf = new SimpleDateFormat(format);
  194. birthday.setTime(sdf.parse(birthString));
  195. age = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
  196. if (!isNominalAge) {
  197. if (today.get(Calendar.MONTH) < birthday.get(Calendar.MONTH) ||
  198. (today.get(Calendar.MONTH) == birthday.get(Calendar.MONTH) &&
  199. today.get(Calendar.DAY_OF_MONTH) < birthday.get(Calendar.DAY_OF_MONTH))) {
  200. age = age - 1;
  201. }
  202. }
  203. 复制代码
  204. } catch (ParseException e) { e.printStackTrace(); }
  205. return age;
  206. }
  207. /**
  208. * 手机号中间四位替换成星号
  209. *
  210. * @param mobile
  211. * @return */ public static String maskMobile(String mobile) { if (validateMobile(mobile)) { return mobile.replaceAll("(d{3})d{4}(d{4})", "$1****$2"); } return mobile; }
  212. /**
  213. * 手机号中间四位自定义替换
  214. *
  215. * @param mobile
  216. * @param transCode 中间四位目标值 如GXJF 将136GXJF1111
  217. * @return */ public static String maskMobile(String mobile, String transCode) { if (validateMobile(mobile)) { transCode = StringUtils.isEmpty(transCode) ? "****" : transCode; return mobile.replaceAll("(d{3})d{4}(d{4})", String.format("$1%s$2", transCode)); } return mobile; }
  218. /**
  219. * 邮箱地址加星号
  220. *
  221. * @param email
  222. * @return */ public static String maskEmail(String email) { if (validateEmail(email)) { String userName = email.substring(0, email.indexOf("@")); int len = userName.length(); if (len >= 5) { int total = len - 3; int half = total / 2; int start = half; int end = len - half; if (total % 2 != 0) { end = end - 1; } StringBuilder sb = new StringBuilder(email); for (int i = start; i < end; i++) { sb.setCharAt(i, '*'); } return sb.toString(); } } return email; }
  223. /**
  224. * 账号中间四位自定义替换
  225. *
  226. * @param account
  227. * @return */ public static String maskTradeAccount(String account) { return account.replaceAll("(d{7})d*(d{4})", "$1****$2"); }
  228. /**
  229. * 读取jsonResult的value中的某个属性值
  230. *
  231. * @param jsonResult
  232. * @param attrName
  233. * @return */
  234. public static String readJSONResultValueAttr(JSONResult jsonResult, String attrName) { String ret = ""; try { ret = ((JSONObject) jsonResult.getValue()).get(attrName).toString(); } catch (Exception e) { [//e.printStackTrace][e.printStackTrace](); } return ret; }
  235. /**
  236. * 验证是否为日期
  237. *
  238. * @param date
  239. * @return */ public static boolean validateDate(String date) { boolean convertSuccess = true; SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); try { format.setLenient(false); format.parse(date); } catch (ParseException e) { convertSuccess = false; } return convertSuccess; }
  240. /**
  241. * 获取时间戳,作为递增的ID */ private static final Lock lock = new ReentrantLock(); //锁对象
  242. public static long getUniqueLong() { long l; lock.lock(); try { l = System.currentTimeMillis(); } finally { lock.unlock(); } return l; }
  243. /**
  244. * 解析出url参数中的键值对
  245. * 如 "index.jsp?Action=del&id=123",解析出Action:del,id:123存入map中
  246. *
  247. * @param URL url地址
  248. * @return url请求参数部分 */ public static String getUrlParams(String URL, String key) { Map<String, String> mapRequest = new HashMap<String, String>(); String[] arrSplit = null; String strUrlParam = null; java.net.URL aURL = null; try { aURL = new URL(URL); strUrlParam = aURL.getQuery(); } catch (MalformedURLException e) { e.printStackTrace(); } if (strUrlParam == null) { return ""; } arrSplit = strUrlParam.split("[&]"); for (String strSplit : arrSplit) { String[] arrSplitEqual = null; arrSplitEqual = strSplit.split("[=]"); if (arrSplitEqual.length > 1) { mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]); } else { if (!StringUtils.isEmpty(arrSplitEqual[0])) { mapRequest.put(arrSplitEqual[0], ""); } } } if (mapRequest.containsKey(key)) { try { return URLDecoder.decode(mapRequest.get(key), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) {
  249. }
  250. } return ""; }
  1. /**
  2. * 生成随机密码
  3. *
  4. * @param pwd_len 生成的密码的总长度
  5. * @return 密码的字符串 */ public static String genRandomNum(int pwd_len) { // 35是因为数组是从0开始的,26个字母+10个数字 final int maxNum = 36; int i; // 生成的随机数 int count = 0; // 生成的密码的长度 char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; StringBuffer pwd = new StringBuffer(""); Random r = new Random(); while (count < pwd_len) { // 生成随机数,取绝对值,防止生成负数, i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1 if (i >= 0 && i < str.length) { pwd.append(str[i]); count++; } } return pwd.toString(); }
  6. }

如果想学习Java工程化、高性能及分布式、深入浅出。性能调优、Spring,MyBatis,Netty源码分析的朋友可以加我的Java高级程序员群:180705916,群里有阿里大牛直播讲解技术,以及Java大型互联网技术的视频免费分享给大家。

发表评论

表情:
评论列表 (有 0 条评论,689人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android开发工具

    不管是前端,后端,还是我们的android开发,实际工作中都会用到很多的工具类,这些工具类会让我们工作更加得心应手,同样,每一位开发者工作一定年限后都有自己的代码库,所以能适应