Java常用工具类---XML工具类、数据验证工具类

野性酷女 2022-01-29 10:04 493阅读 0赞
  1. package com.jarvis.base.util;
  2. import java.io.File;
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5. import java.io.StringReader;
  6. import java.io.StringWriter;
  7. import java.net.URL;
  8. import java.util.Properties;
  9. import javax.xml.transform.OutputKeys;
  10. import javax.xml.transform.Result;
  11. import javax.xml.transform.Source;
  12. import javax.xml.transform.Transformer;
  13. import javax.xml.transform.TransformerFactory;
  14. import javax.xml.transform.stream.StreamResult;
  15. import javax.xml.transform.stream.StreamSource;
  16. import org.dom4j.Document;
  17. import org.dom4j.Element;
  18. import org.dom4j.io.OutputFormat;
  19. import org.dom4j.io.SAXReader;
  20. import org.dom4j.io.XMLWriter;
  21. /**
  22. *
  23. *
  24. * @Title: XMLHelper.java
  25. * @Package com.jarvis.base.util
  26. * @Description:XML工具类
  27. * @version V1.0
  28. */
  29. public final class XMLHelper {
  30. /**
  31. * 把XML按照给定的XSL进行转换,返回转换后的值
  32. *
  33. * @param xml
  34. * xml
  35. * @param xsl
  36. * xsl
  37. * @return
  38. * @throws Exception
  39. */
  40. public static String xml2xsl(String xml, URL xsl) throws Exception {
  41. if (StringHelper.isEmpty(xml)) {
  42. throw new Exception("xml string is empty");
  43. }
  44. if (xsl == null) {
  45. throw new Exception("xsl string is empty");
  46. }
  47. StringWriter writer = new StringWriter();
  48. Source xmlSource = null;
  49. Source xslSource = null;
  50. Result result = null;
  51. try {
  52. xmlSource = new StreamSource(new StringReader(xml));
  53. xslSource = new StreamSource(xsl.openStream());
  54. result = new StreamResult(writer);
  55. TransformerFactory transFact = TransformerFactory.newInstance();
  56. Transformer trans = transFact.newTransformer(xslSource);
  57. trans.transform(xmlSource, result);
  58. return writer.toString();
  59. } catch (Exception ex) {
  60. throw new Exception(ex);
  61. } finally {
  62. writer.close();
  63. writer = null;
  64. xmlSource = null;
  65. xslSource = null;
  66. result = null;
  67. }
  68. }
  69. /**
  70. * 把XML按用户定义好的XSL样式进行输出
  71. *
  72. * @param xmlFilePath
  73. * XML文档
  74. * @param xsl
  75. * XSL样式
  76. * @return 样式化后的字段串
  77. */
  78. public static String xml2xsl(String xmlFilePath, String xsl) throws Exception {
  79. if (StringHelper.isEmpty(xmlFilePath)) {
  80. throw new Exception("xml string is empty");
  81. }
  82. if (StringHelper.isEmpty(xsl)) {
  83. throw new Exception("xsl string is empty");
  84. }
  85. StringWriter writer = new StringWriter();
  86. Source xmlSource = new StreamSource(new File(xmlFilePath));
  87. Source xslSource = new StreamSource(new File(xsl));
  88. Result result = new StreamResult(writer);
  89. try {
  90. TransformerFactory transFact = TransformerFactory.newInstance();
  91. Transformer trans = transFact.newTransformer(xslSource);
  92. Properties properties = trans.getOutputProperties();
  93. properties.setProperty(OutputKeys.ENCODING, "UTF-8");
  94. properties.put(OutputKeys.METHOD, "html");
  95. trans.setOutputProperties(properties);
  96. trans.transform(xmlSource, result);
  97. return writer.toString();
  98. } finally {
  99. writer.close();
  100. writer = null;
  101. xmlSource = null;
  102. xslSource = null;
  103. result = null;
  104. }
  105. }
  106. /**
  107. * 读取XML文档,返回Document对象.<br>
  108. *
  109. * @param xmlFile
  110. * XML文件路径
  111. * @return Document 对象
  112. */
  113. public static Document getDocument(String xmlFile) throws Exception {
  114. if (StringHelper.isEmpty(xmlFile)) {
  115. return null;
  116. }
  117. File file = null;
  118. SAXReader saxReader = new SAXReader();
  119. file = new File(xmlFile);
  120. return saxReader.read(file);
  121. }
  122. /**
  123. * 读取XML文档,返回Document对象.<br>
  124. *
  125. * @param xmlFile
  126. * file对象
  127. * @return Document 对象
  128. */
  129. public static Document getDocument(File xmlFile) {
  130. try {
  131. SAXReader saxReader = new SAXReader();
  132. return saxReader.read(xmlFile);
  133. } catch (Exception ex) {
  134. ex.printStackTrace();
  135. System.err.println("读取xml文件出错,返回null");
  136. return null;
  137. }
  138. }
  139. /**
  140. * 读取XML字串,返回Document对象
  141. *
  142. * @param xmlString
  143. * XML文件路径
  144. * @return Document 对象
  145. */
  146. public static Document getDocumentFromString(String xmlString) {
  147. if (StringHelper.isEmpty(xmlString)) {
  148. return null;
  149. }
  150. try {
  151. SAXReader saxReader = new SAXReader();
  152. return saxReader.read(new StringReader(xmlString));
  153. } catch (Exception ex) {
  154. ex.printStackTrace();
  155. System.err.println("读取xml文件出错,返回null");
  156. return null;
  157. }
  158. }
  159. /**
  160. * 描述:把xml输出成为html 作者: 时间:Oct 29, 2008 4:57:56 PM
  161. *
  162. * @param xmlDoc
  163. * xmlDoc
  164. * @param xslFile
  165. * xslFile
  166. * @param encoding
  167. * 编码
  168. * @return
  169. * @throws Exception
  170. */
  171. public static String xml2html(String xmlDoc, String xslFile, String encoding) throws Exception {
  172. if (StringHelper.isEmpty(xmlDoc)) {
  173. throw new Exception("xml string is empty");
  174. }
  175. if (StringHelper.isEmpty(xslFile)) {
  176. throw new Exception("xslt file is empty");
  177. }
  178. StringWriter writer = new StringWriter();
  179. Source xmlSource = null;
  180. Source xslSource = null;
  181. Result result = null;
  182. String html = null;
  183. try {
  184. xmlSource = new StreamSource(new StringReader(xmlDoc));
  185. xslSource = new StreamSource(new File(xslFile));
  186. result = new StreamResult(writer);
  187. TransformerFactory transFact = TransformerFactory.newInstance();
  188. Transformer trans = transFact.newTransformer(xslSource);
  189. Properties properties = trans.getOutputProperties();
  190. properties.put(OutputKeys.METHOD, "html");
  191. properties.setProperty(OutputKeys.ENCODING, encoding);
  192. trans.setOutputProperties(properties);
  193. trans.transform(xmlSource, result);
  194. html = writer.toString();
  195. writer.close();
  196. return html;
  197. } catch (Exception ex) {
  198. throw new Exception(ex);
  199. } finally {
  200. writer = null;
  201. xmlSource = null;
  202. xslSource = null;
  203. result = null;
  204. }
  205. }
  206. /**
  207. * 描述:把xml输出成为html
  208. *
  209. * @param xmlFile
  210. * xmlFile
  211. * @param xslFile
  212. * xslFile
  213. * @param encoding
  214. * 编码
  215. * @return
  216. * @throws Exception
  217. */
  218. public static String xmlFile2html(String xmlFile, String xslFile, String encoding) throws Exception {
  219. if (StringHelper.isEmpty(xmlFile)) {
  220. throw new Exception("xml string is empty");
  221. }
  222. if (StringHelper.isEmpty(xslFile)) {
  223. throw new Exception("xslt file is empty");
  224. }
  225. StringWriter writer = new StringWriter();
  226. Source xmlSource = null;
  227. Source xslSource = null;
  228. Result result = null;
  229. String html = null;
  230. try {
  231. xmlSource = new StreamSource(new File(xmlFile));
  232. xslSource = new StreamSource(new File(xslFile));
  233. result = new StreamResult(writer);
  234. TransformerFactory transFact = TransformerFactory.newInstance();
  235. Transformer trans = transFact.newTransformer(xslSource);
  236. Properties properties = trans.getOutputProperties();
  237. properties.put(OutputKeys.METHOD, "html");
  238. properties.setProperty(OutputKeys.ENCODING, encoding);
  239. trans.setOutputProperties(properties);
  240. trans.transform(xmlSource, result);
  241. html = writer.toString();
  242. writer.close();
  243. return html;
  244. } catch (Exception ex) {
  245. throw new Exception(ex);
  246. } finally {
  247. writer = null;
  248. xmlSource = null;
  249. xslSource = null;
  250. result = null;
  251. }
  252. }
  253. /**
  254. * 描述:
  255. *
  256. * @param name
  257. * 名
  258. * @param element
  259. * 元素
  260. * @return
  261. */
  262. public static String getString(String name, Element element) {
  263. return (element.valueOf(name) == null) ? "" : element.valueOf(name);
  264. }
  265. /**
  266. * 将一个XML文档保存至文件中.
  267. *
  268. * @param doc
  269. * 要保存的XML文档对象.
  270. * @param filePath
  271. * 要保存到的文档路径.
  272. * @param format
  273. * 要保存的输出格式
  274. * @return true代表保存成功,否则代表不成功.
  275. */
  276. public static boolean savaToFile(Document doc, String filePathName, OutputFormat format) {
  277. XMLWriter writer;
  278. try {
  279. String filePath = FileHelper.getFullPath(filePathName);
  280. // 若目录不存在,则建立目录
  281. if (!FileHelper.exists(filePath)) {
  282. if (!FileHelper.createDirectory(filePath)) {
  283. return false;
  284. }
  285. }
  286. writer = new XMLWriter(new FileWriter(new File(filePathName)), format);
  287. writer.write(doc);
  288. writer.close();
  289. return true;
  290. } catch (IOException ex) {
  291. ex.printStackTrace();
  292. System.err.println("写文件出错");
  293. }
  294. return false;
  295. }
  296. /**
  297. * 将一个XML文档保存至文件中.
  298. *
  299. * @param filePath
  300. * 要保存到的文档路径.
  301. * @param doc
  302. * 要保存的XML文档对象.
  303. * @return true代表保存成功,否则代表不成功.
  304. */
  305. public static boolean writeToXml(String filePathName, Document doc) {
  306. OutputFormat format = OutputFormat.createCompactFormat();
  307. format.setEncoding("UTF-8");
  308. return savaToFile(doc, filePathName, format);
  309. }
  310. }
  311. package com.jarvis.base.util;
  312. import java.text.ParseException;
  313. import java.text.SimpleDateFormat;
  314. import java.util.Calendar;
  315. import java.util.Date;
  316. import java.util.regex.Matcher;
  317. import java.util.regex.Pattern;
  318. /**
  319. * 说明: 常用的数据验证工具类。
  320. *
  321. */
  322. public class ValidateUtil {
  323. public static final Pattern CODE_PATTERN = Pattern.compile("^0\\d{2,4}$");
  324. public static final Pattern POSTCODE_PATTERN = Pattern.compile("^\\d{6}$");
  325. public static final Pattern BANK_CARD_PATTERN = Pattern.compile("^\\d{16,30}$");
  326. /**
  327. * 匹配图象
  328. *
  329. *
  330. * 格式: /相对路径/文件名.后缀 (后缀为gif,dmp,png)
  331. *
  332. * 匹配 : /forum/head_icon/admini2005111_ff.gif 或 admini2005111.dmp
  333. *
  334. *
  335. * 不匹配: c:/admins4512.gif
  336. *
  337. */
  338. public static final String ICON_REGEXP = "^(/{0,1}//w){1,}//.(gif|dmp|png|jpg)$|^//w{1,}//.(gif|dmp|png|jpg)$";
  339. /**
  340. * 匹配email地址
  341. *
  342. *
  343. * 格式: XXX@XXX.XXX.XX
  344. *
  345. * 匹配 : foo@bar.com 或 foobar@foobar.com.au
  346. *
  347. * 不匹配: foo@bar 或 $$$@bar.com
  348. *
  349. */
  350. public static final String EMAIL_REGEXP = "(?://w[-._//w]*//w@//w[-._//w]*//w//.//w{2,3}$)";
  351. /**
  352. * 匹配并提取url
  353. *
  354. *
  355. * 格式: XXXX://XXX.XXX.XXX.XX/XXX.XXX?XXX=XXX
  356. *
  357. * 匹配 : http://www.suncer.com 或news://www
  358. *
  359. * 不匹配: c:/window
  360. *
  361. */
  362. public static final String URL_REGEXP = "(//w+)://([^/:]+)(://d*)?([^#//s]*)";
  363. /**
  364. * 匹配并提取http
  365. *
  366. * 格式: http://XXX.XXX.XXX.XX/XXX.XXX?XXX=XXX 或 ftp://XXX.XXX.XXX 或
  367. * https://XXX
  368. *
  369. * 匹配 : http://www.suncer.com:8080/index.html?login=true
  370. *
  371. * 不匹配: news://www
  372. *
  373. */
  374. public static final String HTTP_REGEXP = "(http|https|ftp)://([^/:]+)(://d*)?([^#//s]*)";
  375. /**
  376. * 匹配日期
  377. *
  378. *
  379. * 格式(首位不为0): XXXX-XX-XX或 XXXX-X-X
  380. *
  381. *
  382. * 范围:1900--2099
  383. *
  384. *
  385. * 匹配 : 2005-04-04
  386. *
  387. *
  388. * 不匹配: 01-01-01
  389. *
  390. */
  391. public static final String DATE_BARS_REGEXP = "^((((19){1}|(20){1})\\d{2})|\\d{2})-[0,1]?\\d{1}-[0-3]?\\d{1}$";
  392. /**
  393. * 匹配日期
  394. *
  395. *
  396. * 格式: XXXX/XX/XX
  397. *
  398. *
  399. * 范围:
  400. *
  401. *
  402. * 匹配 : 2005/04/04
  403. *
  404. *
  405. * 不匹配: 01/01/01
  406. *
  407. */
  408. public static final String DATE_SLASH_REGEXP = "^[0-9]{4}/(((0[13578]|(10|12))/(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)/(0[1-9]|[1-2][0-9]|30)))$";
  409. /**
  410. * 匹配电话
  411. *
  412. *
  413. * 格式为: 0XXX-XXXXXX(10-13位首位必须为0) 或0XXX XXXXXXX(10-13位首位必须为0) 或
  414. *
  415. * (0XXX)XXXXXXXX(11-14位首位必须为0) 或 XXXXXXXX(6-8位首位不为0) 或
  416. * XXXXXXXXXXX(11位首位不为0)
  417. *
  418. *
  419. * 匹配 : 0371-123456 或 (0371)1234567 或 (0371)12345678 或 010-123456 或
  420. * 010-12345678 或 12345678912
  421. *
  422. *
  423. * 不匹配: 1111-134355 或 0123456789
  424. *
  425. */
  426. public static final String PHONE_REGEXP = "^(?:0[0-9]{2,3}[-//s]{1}|//(0[0-9]{2,4}//))[0-9]{6,8}$|^[1-9]{1}[0-9]{5,7}$|^[1-9]{1}[0-9]{10}$";
  427. /**
  428. * 匹配身份证
  429. *
  430. * 格式为: XXXXXXXXXX(10位) 或 XXXXXXXXXXXXX(13位) 或 XXXXXXXXXXXXXXX(15位) 或
  431. * XXXXXXXXXXXXXXXXXX(18位)
  432. *
  433. * 匹配 : 0123456789123
  434. *
  435. * 不匹配: 0123456
  436. *
  437. */
  438. public static final String ID_CARD_REGEXP = "^//d{10}|//d{13}|//d{15}|//d{18}$";
  439. /**
  440. * 匹配邮编代码
  441. *
  442. * 格式为: XXXXXX(6位)
  443. *
  444. * 匹配 : 012345
  445. *
  446. * 不匹配: 0123456
  447. *
  448. */
  449. public static final String ZIP_REGEXP = "^[0-9]{6}$";// 匹配邮编代码
  450. /**
  451. * 不包括特殊字符的匹配 (字符串中不包括符号 数学次方号^ 单引号' 双引号" 分号; 逗号, 帽号: 数学减号- 右尖括号> 左尖括号< 反斜杠/
  452. * 即空格,制表符,回车符等 )
  453. *
  454. * 格式为: x 或 一个一上的字符
  455. *
  456. * 匹配 : 012345
  457. *
  458. * 不匹配: 0123456 // ;,:-<>//s].+$";//
  459. */
  460. public static final String NON_SPECIAL_CHAR_REGEXP = "^[^'/";
  461. // 匹配邮编代码
  462. /**
  463. * 匹配非负整数(正整数 + 0)
  464. */
  465. public static final String NON_NEGATIVE_INTEGERS_REGEXP = "^//d+$";
  466. /**
  467. * 匹配不包括零的非负整数(正整数 > 0)
  468. */
  469. public static final String NON_ZERO_NEGATIVE_INTEGERS_REGEXP = "^[1-9]+//d*$";
  470. /**
  471. *
  472. * 匹配正整数
  473. *
  474. */
  475. public static final String POSITIVE_INTEGER_REGEXP = "^[0-9]*[1-9][0-9]*$";
  476. /**
  477. *
  478. * 匹配非正整数(负整数 + 0)
  479. *
  480. */
  481. public static final String NON_POSITIVE_INTEGERS_REGEXP = "^((-//d+)|(0+))$";
  482. /**
  483. *
  484. * 匹配负整数
  485. *
  486. */
  487. public static final String NEGATIVE_INTEGERS_REGEXP = "^-[0-9]*[1-9][0-9]*$";
  488. /**
  489. *
  490. * 匹配整数
  491. *
  492. */
  493. public static final String INTEGER_REGEXP = "^-?//d+$";
  494. /**
  495. *
  496. * 匹配非负浮点数(正浮点数 + 0)
  497. *
  498. */
  499. public static final String NON_NEGATIVE_RATIONAL_NUMBERS_REGEXP = "^//d+(//.//d+)?$";
  500. /**
  501. *
  502. * 匹配正浮点数
  503. *
  504. */
  505. public static final String POSITIVE_RATIONAL_NUMBERS_REGEXP = "^(([0-9]+//.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*//.[0-9]+)|([0-9]*[1-9][0-9]*))$";
  506. /**
  507. *
  508. * 匹配非正浮点数(负浮点数 + 0)
  509. *
  510. */
  511. public static final String NON_POSITIVE_RATIONAL_NUMBERS_REGEXP = "^((-//d+(//.//d+)?)|(0+(//.0+)?))$";
  512. /**
  513. *
  514. * 匹配负浮点数
  515. *
  516. */
  517. public static final String NEGATIVE_RATIONAL_NUMBERS_REGEXP = "^(-(([0-9]+//.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*//.[0-9]+)|([0-9]*[1-9][0-9]*)))$";
  518. /**
  519. *
  520. * 匹配浮点数
  521. *
  522. */
  523. public static final String RATIONAL_NUMBERS_REGEXP = "^(-?//d+)(//.//d+)?$";
  524. /**
  525. *
  526. * 匹配由26个英文字母组成的字符串
  527. *
  528. */
  529. public static final String LETTER_REGEXP = "^[A-Za-z]+$";
  530. /**
  531. *
  532. * 匹配由26个英文字母的大写组成的字符串
  533. *
  534. */
  535. public static final String UPWARD_LETTER_REGEXP = "^[A-Z]+$";
  536. /**
  537. *
  538. * 匹配由26个英文字母的小写组成的字符串
  539. *
  540. */
  541. public static final String LOWER_LETTER_REGEXP = "^[a-z]+$";
  542. /**
  543. *
  544. * 匹配由数字和26个英文字母组成的字符串
  545. *
  546. */
  547. public static final String LETTER_NUMBER_REGEXP = "^[A-Za-z0-9]+$";
  548. /**
  549. *
  550. * 匹配由数字、26个英文字母或者下划线组成的字符串
  551. *
  552. */
  553. public static final String LETTER_NUMBER_UNDERLINE_REGEXP = "^//w+$";
  554. public static boolean validateEmail(String str) {
  555. if (str == null || str.trim().length() == 0) {
  556. return false;
  557. }
  558. Pattern pattern = Pattern.compile(
  559. "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
  560. // Pattern pattern =
  561. // Pattern.compile("^([a-zA-Z0-9_-])+@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}");
  562. Matcher matcher = pattern.matcher(str);
  563. return matcher.matches();
  564. }
  565. public static boolean validateMoblie(String str) {
  566. if (str == null || str.trim().length() == 0) {
  567. return false;
  568. }
  569. Pattern pattern = Pattern.compile("^(13|14|15|17|18)[0-9]{9}$");
  570. Matcher matcher = pattern.matcher(str);
  571. return matcher.matches();
  572. }
  573. /**
  574. * 验证区号是否有效.
  575. *
  576. * @param code 要验证的区号
  577. * @return 是否正确身份证
  578. */
  579. public static boolean validateCode(String code) {
  580. if (StringHelper.isEmpty(code)) {
  581. return false;
  582. }
  583. Matcher m = CODE_PATTERN.matcher(code);
  584. return m.matches();
  585. }
  586. /**
  587. * 验证邮政编码是否有效.
  588. *
  589. * @param postcode 要验证的邮政编码
  590. * @return 是否正确邮政编码
  591. */
  592. public static boolean validatePostcode(String postcode) {
  593. if (StringHelper.isEmpty(postcode)) {
  594. return false;
  595. }
  596. Matcher m = POSTCODE_PATTERN.matcher(postcode);
  597. return m.matches();
  598. }
  599. /**
  600. * 验证银行卡是否有效.
  601. *
  602. * @param bankCardNumber 要验证的银行卡号
  603. * @return 是否正确银行卡号
  604. */
  605. public static boolean validateBankCardNumber(String bankCardNumber) {
  606. if (StringHelper.isEmpty(bankCardNumber)) {
  607. return false;
  608. }
  609. Matcher m = BANK_CARD_PATTERN.matcher(bankCardNumber);
  610. return m.matches();
  611. }
  612. /**
  613. * 通过身份证获取生日
  614. *
  615. * @param idNumber 身份证号
  616. * @return 返回生日, 格式为 yyyy-MM-dd 的字符串
  617. */
  618. public static String getBirthdayByIdNumber(String idNumber) {
  619. String birthday = "";
  620. if (idNumber.length() == 15) {
  621. birthday = "19" + idNumber.substring(6, 8) + "-" + idNumber.substring(8, 10) + "-" + idNumber.substring(10, 12);
  622. } else if (idNumber.length() == 18) {
  623. birthday = idNumber.substring(6, 10) + "-" + idNumber.substring(10, 12) + "-" + idNumber.substring(12, 14);
  624. }
  625. return birthday;
  626. }
  627. /**
  628. * 通过身份证获取性别
  629. *
  630. * @param idNumber 身份证号
  631. * @return 返回性别, 0 保密 , 1 男 2 女
  632. */
  633. public static Integer getGenderByIdNumber(String idNumber) {
  634. int gender = 0;
  635. if (idNumber.length() == 15) {
  636. gender = Integer.parseInt(String.valueOf(idNumber.charAt(14))) % 2 == 0 ? 2 : 1;
  637. } else if (idNumber.length() == 18) {
  638. gender = Integer.parseInt(String.valueOf(idNumber.charAt(16))) % 2 == 0 ? 2 : 1;
  639. }
  640. return gender;
  641. }
  642. /**
  643. * 通过身份证获取年龄
  644. *
  645. * @param idNumber 身份证号
  646. * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  647. * @return 返回年龄
  648. */
  649. public static Integer getAgeByIdNumber(String idNumber, boolean isNominalAge) {
  650. String birthString = getBirthdayByIdNumber(idNumber);
  651. if (StringHelper.isEmpty(birthString)) {
  652. return 0;
  653. }
  654. return getAgeByBirthString(birthString, isNominalAge);
  655. }
  656. /**
  657. * 通过生日日期获取年龄
  658. *
  659. * @param birthDate 生日日期
  660. * @return 返回年龄
  661. */
  662. public static Integer getAgeByBirthDate(Date birthDate) {
  663. return getAgeByBirthString(new SimpleDateFormat("yyyy-MM-dd").format(birthDate));
  664. }
  665. /**
  666. * 通过生日字符串获取年龄
  667. *
  668. * @param birthString 生日字符串
  669. * @return 返回年龄
  670. */
  671. public static Integer getAgeByBirthString(String birthString) {
  672. return getAgeByBirthString(birthString, "yyyy-MM-dd");
  673. }
  674. /**
  675. * 通过生日字符串获取年龄
  676. *
  677. * @param birthString 生日字符串
  678. * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  679. * @return 返回年龄
  680. */
  681. public static Integer getAgeByBirthString(String birthString, boolean isNominalAge) {
  682. return getAgeByBirthString(birthString, "yyyy-MM-dd", isNominalAge);
  683. }
  684. /**
  685. * 通过生日字符串获取年龄
  686. *
  687. * @param birthString 生日字符串
  688. * @param format 日期字符串格式,为空则默认"yyyy-MM-dd"
  689. * @return 返回年龄
  690. */
  691. public static Integer getAgeByBirthString(String birthString, String format) {
  692. return getAgeByBirthString(birthString, "yyyy-MM-dd", false);
  693. }
  694. /**
  695. * 通过生日字符串获取年龄
  696. *
  697. * @param birthString 生日字符串
  698. * @param format 日期字符串格式,为空则默认"yyyy-MM-dd"
  699. * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  700. * @return 返回年龄
  701. */
  702. public static Integer getAgeByBirthString(String birthString, String format, boolean isNominalAge) {
  703. int age = 0;
  704. if (StringHelper.isEmpty(birthString)) {
  705. return age;
  706. }
  707. if (StringHelper.isEmpty(format)) {
  708. format = "yyyy-MM-dd";
  709. }
  710. try {
  711. Calendar birthday = Calendar.getInstance();
  712. Calendar today = Calendar.getInstance();
  713. SimpleDateFormat sdf = new SimpleDateFormat(format);
  714. birthday.setTime(sdf.parse(birthString));
  715. age = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
  716. if (!isNominalAge) {
  717. if (today.get(Calendar.MONTH) < birthday.get(Calendar.MONTH) ||
  718. (today.get(Calendar.MONTH) == birthday.get(Calendar.MONTH) &&
  719. today.get(Calendar.DAY_OF_MONTH) < birthday.get(Calendar.DAY_OF_MONTH))) {
  720. age = age - 1;
  721. }
  722. }
  723. } catch (ParseException e) {
  724. e.printStackTrace();
  725. }
  726. return age;
  727. }
  728. /**
  729. * 大小写敏感的正规表达式批配
  730. *
  731. * @param source
  732. * 批配的源字符串
  733. * @param regexp
  734. * 批配的正规表达式
  735. * @return 如果源字符串符合要求返回真,否则返回假
  736. */
  737. public static boolean isHardRegexpValidate(String str, String regexp) {
  738. if (str == null || str.trim().length() == 0) {
  739. return false;
  740. }
  741. Pattern pattern = Pattern.compile(regexp);
  742. Matcher matcher = pattern.matcher(str);
  743. return matcher.matches();
  744. }
  745. }

发表评论

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

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

相关阅读