当前位置:主页 > java教程 > java常用工具类代码详解

java常用工具类 UUID、Map工具类、XML工具类、数据验证工具类

发布:2019-05-31 10:21:12 17


给寻找编程代码教程的朋友们精选了相关的编程文章,网友梁开琼根据主题投稿了本篇教程内容,涉及到java、工具类、UUID、Map、XML、数据验证、java常用工具类代码详解相关内容,已被965网友关注,下面的电子资料对本篇知识点有更加详尽的解释。

java常用工具类代码详解

297

java常用工具类 XML工具类、数据验证工具类

本文实例为大家分享了java常用工具类的具体代码,供大家参考,具体内容如下

package com.jarvis.base.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.Properties;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 
 * 
 * @Title: XMLHelper.java
 * @Package com.jarvis.base.util
 * @Description:XML工具类
 * @version V1.0 
 */
public final class XMLHelper {
 /**
 * 把XML按照给定的XSL进行转换,返回转换后的值
 *
 * @param xml
 *   xml
 * @param xsl
 *   xsl
 * @return
 * @throws Exception
 */
 public static String xml2xsl(String xml, URL xsl) throws Exception {
 if (StringHelper.isEmpty(xml)) {
 throw new Exception("xml string is empty");
 }
 if (xsl == null) {
 throw new Exception("xsl string is empty");
 }

 StringWriter writer = new StringWriter();
 Source xmlSource = null;
 Source xslSource = null;
 Result result = null;

 try {
 xmlSource = new StreamSource(new StringReader(xml));
 xslSource = new StreamSource(xsl.openStream());
 result = new StreamResult(writer);

 TransformerFactory transFact = TransformerFactory.newInstance();
 Transformer trans = transFact.newTransformer(xslSource);
 trans.transform(xmlSource, result);
 return writer.toString();
 } catch (Exception ex) {
 throw new Exception(ex);
 } finally {
 writer.close();
 writer = null;
 xmlSource = null;
 xslSource = null;
 result = null;
 }
 }

 /**
 * 把XML按用户定义好的XSL样式进行输出
 *
 * @param xmlFilePath
 *   XML文档
 * @param xsl
 *   XSL样式
 * @return 样式化后的字段串
 */
 public static String xml2xsl(String xmlFilePath, String xsl) throws Exception {
 if (StringHelper.isEmpty(xmlFilePath)) {
 throw new Exception("xml string is empty");
 }
 if (StringHelper.isEmpty(xsl)) {
 throw new Exception("xsl string is empty");
 }

 StringWriter writer = new StringWriter();
 Source xmlSource = new StreamSource(new File(xmlFilePath));
 Source xslSource = new StreamSource(new File(xsl));
 Result result = new StreamResult(writer);

 try {
 TransformerFactory transFact = TransformerFactory.newInstance();
 Transformer trans = transFact.newTransformer(xslSource);
 Properties properties = trans.getOutputProperties();
 properties.setProperty(OutputKeys.ENCODING, "UTF-8");
 properties.put(OutputKeys.METHOD, "html");
 trans.setOutputProperties(properties);

 trans.transform(xmlSource, result);
 return writer.toString();
 } finally {
 writer.close();
 writer = null;

 xmlSource = null;
 xslSource = null;
 result = null;
 }
 }

 /**
 * 读取XML文档,返回Document对象.<br>
 *
 * @param xmlFile
 *   XML文件路径
 * @return Document 对象
 */
 public static Document getDocument(String xmlFile) throws Exception {
 if (StringHelper.isEmpty(xmlFile)) {
 return null;
 }

 File file = null;
 SAXReader saxReader = new SAXReader();

 file = new File(xmlFile);
 return saxReader.read(file);
 }

 /**
 * 读取XML文档,返回Document对象.<br>
 *
 * @param xmlFile
 *   file对象
 * @return Document 对象
 */
 public static Document getDocument(File xmlFile) {
 try {
 SAXReader saxReader = new SAXReader();
 return saxReader.read(xmlFile);
 } catch (Exception ex) {
 ex.printStackTrace();
 System.err.println("读取xml文件出错,返回null");
 return null;
 }
 }

 /**
 * 读取XML字串,返回Document对象
 *
 * @param xmlString
 *   XML文件路径
 * @return Document 对象
 */
 public static Document getDocumentFromString(String xmlString) {
 if (StringHelper.isEmpty(xmlString)) {
 return null;
 }
 try {
 SAXReader saxReader = new SAXReader();
 return saxReader.read(new StringReader(xmlString));
 } catch (Exception ex) {
 ex.printStackTrace();
 System.err.println("读取xml文件出错,返回null");
 return null;
 }
 }

 /**
 * 描述:把xml输出成为html 作者: 时间:Oct 29, 2008 4:57:56 PM
 * 
 * @param xmlDoc
 *   xmlDoc
 * @param xslFile
 *   xslFile
 * @param encoding
 *   编码
 * @return
 * @throws Exception
 */
 public static String xml2html(String xmlDoc, String xslFile, String encoding) throws Exception {
 if (StringHelper.isEmpty(xmlDoc)) {
 throw new Exception("xml string is empty");
 }
 if (StringHelper.isEmpty(xslFile)) {
 throw new Exception("xslt file is empty");
 }

 StringWriter writer = new StringWriter();
 Source xmlSource = null;
 Source xslSource = null;
 Result result = null;
 String html = null;
 try {
 xmlSource = new StreamSource(new StringReader(xmlDoc));
 xslSource = new StreamSource(new File(xslFile));

 result = new StreamResult(writer);

 TransformerFactory transFact = TransformerFactory.newInstance();
 Transformer trans = transFact.newTransformer(xslSource);
 Properties properties = trans.getOutputProperties();
 properties.put(OutputKeys.METHOD, "html");
 properties.setProperty(OutputKeys.ENCODING, encoding);
 trans.setOutputProperties(properties);

 trans.transform(xmlSource, result);

 html = writer.toString();
 writer.close();

 return html;
 } catch (Exception ex) {
 throw new Exception(ex);
 } finally {
 writer = null;

 xmlSource = null;
 xslSource = null;
 result = null;
 }
 }

 /**
 * 描述:把xml输出成为html
 * 
 * @param xmlFile
 *   xmlFile
 * @param xslFile
 *   xslFile
 * @param encoding
 *   编码
 * @return
 * @throws Exception
 */
 public static String xmlFile2html(String xmlFile, String xslFile, String encoding) throws Exception {
 if (StringHelper.isEmpty(xmlFile)) {
 throw new Exception("xml string is empty");
 }
 if (StringHelper.isEmpty(xslFile)) {
 throw new Exception("xslt file is empty");
 }

 StringWriter writer = new StringWriter();
 Source xmlSource = null;
 Source xslSource = null;
 Result result = null;
 String html = null;
 try {
 xmlSource = new StreamSource(new File(xmlFile));
 xslSource = new StreamSource(new File(xslFile));

 result = new StreamResult(writer);

 TransformerFactory transFact = TransformerFactory.newInstance();
 Transformer trans = transFact.newTransformer(xslSource);
 Properties properties = trans.getOutputProperties();
 properties.put(OutputKeys.METHOD, "html");
 properties.setProperty(OutputKeys.ENCODING, encoding);
 trans.setOutputProperties(properties);

 trans.transform(xmlSource, result);

 html = writer.toString();
 writer.close();

 return html;
 } catch (Exception ex) {
 throw new Exception(ex);
 } finally {
 writer = null;

 xmlSource = null;
 xslSource = null;
 result = null;
 }
 }

 /**
 * 描述:
 * 
 * @param name
 *   名
 * @param element
 *   元素
 * @return
 */
 public static String getString(String name, Element element) {
 return (element.valueOf(name) == null) ? "" : element.valueOf(name);
 }

 /**
 * 将一个XML文档保存至文件中.
 *
 * @param doc
 *   要保存的XML文档对象.
 * @param filePath
 *   要保存到的文档路径.
 * @param format
 *   要保存的输出格式
 * @return true代表保存成功,否则代表不成功.
 */
 public static boolean savaToFile(Document doc, String filePathName, OutputFormat format) {
 XMLWriter writer;
 try {
 String filePath = FileHelper.getFullPath(filePathName);
 // 若目录不存在,则建立目录
 if (!FileHelper.exists(filePath)) {
 if (!FileHelper.createDirectory(filePath)) {
  return false;
 }
 }

 writer = new XMLWriter(new FileWriter(new File(filePathName)), format);
 writer.write(doc);
 writer.close();
 return true;
 } catch (IOException ex) {
 ex.printStackTrace();
 System.err.println("写文件出错");
 }

 return false;
 }

 /**
 * 将一个XML文档保存至文件中.
 *
 * @param filePath
 *   要保存到的文档路径.
 * @param doc
 *   要保存的XML文档对象.
 * @return true代表保存成功,否则代表不成功.
 */
 public static boolean writeToXml(String filePathName, Document doc) {
 OutputFormat format = OutputFormat.createCompactFormat();
 format.setEncoding("UTF-8");
 return savaToFile(doc, filePathName, format);
 }
}

数据验证工具类

 

package com.jarvis.base.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 说明: 常用的数据验证工具类。
 *
 */
public class ValidateUtil {

 
 public static final Pattern CODE_PATTERN = Pattern.compile("^0\\d{2,4}$");
 public static final Pattern POSTCODE_PATTERN = Pattern.compile("^\\d{6}$");
 public static final Pattern BANK_CARD_PATTERN = Pattern.compile("^\\d{16,30}$");
 /** 
  * 匹配图象 
  * 
  * 
  * 格式: /相对路径/文件名.后缀 (后缀为gif,dmp,png) 
  * 
  * 匹配 : /forum/head_icon/admini2005111_ff.gif 或 admini2005111.dmp 
  * 
  * 
  * 不匹配: c:/admins4512.gif 
  * 
  */ 
  public static final String ICON_REGEXP = "^(/{0,1}//w){1,}//.(gif|dmp|png|jpg)$|^//w{1,}//.(gif|dmp|png|jpg)$"; 
 
  /** 
  * 匹配email地址 
  * 
  * 
  * 格式: XXX@XXX.XXX.XX 
  * 
  * 匹配 : foo@bar.com 或 foobar@foobar.com.au 
  * 
  * 不匹配: foo@bar 或 $$$@bar.com 
  * 
  */ 
  public static final String EMAIL_REGEXP = "(?://w[-._//w]*//w@//w[-._//w]*//w//.//w{2,3}$)"; 
 
  /** 
  * 匹配并提取url 
  * 
  * 
  * 格式: XXXX://XXX.XXX.XXX.XX/XXX.XXX?XXX=XXX 
  * 
  * 匹配 : http://www.suncer.com 或news://www 
  * 
  * 不匹配: c:/window 
  * 
  */ 
  public static final String URL_REGEXP = "(//w+)://([^/:]+)(://d*)?([^#//s]*)"; 
 
  /** 
  * 匹配并提取http 
  * 
  * 格式: http://XXX.XXX.XXX.XX/XXX.XXX?XXX=XXX 或 ftp://XXX.XXX.XXX 或 
  * https://XXX 
  * 
  * 匹配 : http://www.suncer.com:8080/index.html?login=true 
  * 
  * 不匹配: news://www 
  * 
  */ 
  public static final String HTTP_REGEXP = "(http|https|ftp)://([^/:]+)(://d*)?([^#//s]*)"; 
 
  /** 
  * 匹配日期 
  * 
  * 
  * 格式(首位不为0): XXXX-XX-XX或 XXXX-X-X 
  * 
  * 
  * 范围:1900--2099 
  * 
  * 
  * 匹配 : 2005-04-04 
  * 
  * 
  * 不匹配: 01-01-01 
  * 
  */ 
  public static final String DATE_BARS_REGEXP = "^((((19){1}|(20){1})\\d{2})|\\d{2})-[0,1]?\\d{1}-[0-3]?\\d{1}$"; 
 
  /** 
  * 匹配日期 
  * 
  * 
  * 格式: XXXX/XX/XX 
  * 
  * 
  * 范围: 
  * 
  * 
  * 匹配 : 2005/04/04 
  * 
  * 
  * 不匹配: 01/01/01 
  * 
  */ 
  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)))$"; 
 
  /** 
  * 匹配电话 
  * 
  * 
  * 格式为: 0XXX-XXXXXX(10-13位首位必须为0) 或0XXX XXXXXXX(10-13位首位必须为0) 或 
  * 
  * (0XXX)XXXXXXXX(11-14位首位必须为0) 或 XXXXXXXX(6-8位首位不为0) 或 
  * XXXXXXXXXXX(11位首位不为0) 
  * 
  * 
  * 匹配 : 0371-123456 或 (0371)1234567 或 (0371)12345678 或 010-123456 或 
  * 010-12345678 或 12345678912 
  * 
  * 
  * 不匹配: 1111-134355 或 0123456789 
  * 
  */ 
  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}$"; 
 
  /** 
  * 匹配身份证 
  * 
  * 格式为: XXXXXXXXXX(10位) 或 XXXXXXXXXXXXX(13位) 或 XXXXXXXXXXXXXXX(15位) 或 
  * XXXXXXXXXXXXXXXXXX(18位) 
  * 
  * 匹配 : 0123456789123 
  * 
  * 不匹配: 0123456 
  * 
  */ 
  public static final String ID_CARD_REGEXP = "^//d{10}|//d{13}|//d{15}|//d{18}$"; 
 
  /** 
  * 匹配邮编代码 
  * 
  * 格式为: XXXXXX(6位) 
  * 
  * 匹配 : 012345 
  * 
  * 不匹配: 0123456 
  * 
  */ 
  public static final String ZIP_REGEXP = "^[0-9]{6}$";// 匹配邮编代码 
 
  /** 
  * 不包括特殊字符的匹配 (字符串中不包括符号 数学次方号^ 单引号' 双引号" 分号; 逗号, 帽号: 数学减号- 右尖括号> 左尖括号< 反斜杠/ 
  * 即空格,制表符,回车符等 ) 
  * 
  * 格式为: x 或 一个一上的字符 
  * 
  * 匹配 : 012345 
  * 
  * 不匹配: 0123456 // ;,:-<>//s].+$";// 
  */ 
  public static final String NON_SPECIAL_CHAR_REGEXP = "^[^'/"; 
  // 匹配邮编代码 
 
  /** 
  * 匹配非负整数(正整数 + 0) 
  */ 
  public static final String NON_NEGATIVE_INTEGERS_REGEXP = "^//d+$"; 
 
  /** 
  * 匹配不包括零的非负整数(正整数 > 0) 
  */ 
  public static final String NON_ZERO_NEGATIVE_INTEGERS_REGEXP = "^[1-9]+//d*$"; 
 
  /** 
  * 
  * 匹配正整数 
  * 
  */ 
  public static final String POSITIVE_INTEGER_REGEXP = "^[0-9]*[1-9][0-9]*$"; 
 
  /** 
  * 
  * 匹配非正整数(负整数 + 0) 
  * 
  */ 
  public static final String NON_POSITIVE_INTEGERS_REGEXP = "^((-//d+)|(0+))$"; 
 
  /** 
  * 
  * 匹配负整数 
  * 
  */ 
  public static final String NEGATIVE_INTEGERS_REGEXP = "^-[0-9]*[1-9][0-9]*$"; 
 
  /** 
  * 
  * 匹配整数 
  * 
  */ 
  public static final String INTEGER_REGEXP = "^-?//d+$"; 
 
  /** 
  * 
  * 匹配非负浮点数(正浮点数 + 0) 
  * 
  */ 
  public static final String NON_NEGATIVE_RATIONAL_NUMBERS_REGEXP = "^//d+(//.//d+)?$"; 
 
  /** 
  * 
  * 匹配正浮点数 
  * 
  */ 
  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]*))$"; 
 
  /** 
  * 
  * 匹配非正浮点数(负浮点数 + 0) 
  * 
  */ 
  public static final String NON_POSITIVE_RATIONAL_NUMBERS_REGEXP = "^((-//d+(//.//d+)?)|(0+(//.0+)?))$"; 
 
  /** 
  * 
  * 匹配负浮点数 
  * 
  */ 
  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]*)))$"; 
 
  /** 
  * 
  * 匹配浮点数 
  * 
  */ 
  public static final String RATIONAL_NUMBERS_REGEXP = "^(-?//d+)(//.//d+)?$"; 
 
  /** 
  * 
  * 匹配由26个英文字母组成的字符串 
  * 
  */ 
  public static final String LETTER_REGEXP = "^[A-Za-z]+$"; 
 
  /** 
  * 
  * 匹配由26个英文字母的大写组成的字符串 
  * 
  */ 
  public static final String UPWARD_LETTER_REGEXP = "^[A-Z]+$"; 
 
  /** 
  * 
  * 匹配由26个英文字母的小写组成的字符串 
  * 
  */ 
  public static final String LOWER_LETTER_REGEXP = "^[a-z]+$"; 
 
  /** 
  * 
  * 匹配由数字和26个英文字母组成的字符串 
  * 
  */ 
  public static final String LETTER_NUMBER_REGEXP = "^[A-Za-z0-9]+$"; 
 
  /** 
  * 
  * 匹配由数字、26个英文字母或者下划线组成的字符串 
  * 
  */ 
  public static final String LETTER_NUMBER_UNDERLINE_REGEXP = "^//w+$"; 
 
 
 public static boolean validateEmail(String str) {
 if (str == null || str.trim().length() == 0) {
 return false;
 }
 Pattern pattern = Pattern.compile(
 "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");

 // Pattern pattern =
 // Pattern.compile("^([a-zA-Z0-9_-])+@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}");
 Matcher matcher = pattern.matcher(str);

 return matcher.matches();

 }

 public static boolean validateMoblie(String str) {
 if (str == null || str.trim().length() == 0) {
 return false;
 }
 Pattern pattern = Pattern.compile("^(13|14|15|17|18)[0-9]{9}$");
 Matcher matcher = pattern.matcher(str);

 return matcher.matches();

 }
 
 /**
  * 验证区号是否有效.
  *
  * @param code 要验证的区号
  * @return 是否正确身份证
  */
 public static boolean validateCode(String code) {
  if (StringHelper.isEmpty(code)) {
   return false;
  }
  Matcher m = CODE_PATTERN.matcher(code);
  return m.matches();
 }

 /**
  * 验证邮政编码是否有效.
  *
  * @param postcode 要验证的邮政编码
  * @return 是否正确邮政编码
  */
 public static boolean validatePostcode(String postcode) {
  if (StringHelper.isEmpty(postcode)) {
   return false;
  }
  Matcher m = POSTCODE_PATTERN.matcher(postcode);
  return m.matches();
 }
 
 /**
  * 验证银行卡是否有效.
  *
  * @param bankCardNumber 要验证的银行卡号
  * @return 是否正确银行卡号
  */
 public static boolean validateBankCardNumber(String bankCardNumber) {
  if (StringHelper.isEmpty(bankCardNumber)) {
   return false;
  }
  Matcher m = BANK_CARD_PATTERN.matcher(bankCardNumber);
  return m.matches();
 }
 
 /**
  * 通过身份证获取生日
  *
  * @param idNumber 身份证号
  * @return 返回生日, 格式为 yyyy-MM-dd 的字符串
  */
 public static String getBirthdayByIdNumber(String idNumber) {

  String birthday = "";

  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);
  }

  return birthday;

 }
 
 /**
  * 通过身份证获取性别
  *
  * @param idNumber 身份证号
  * @return 返回性别, 0 保密 , 1 男 2 女
  */
 public static Integer getGenderByIdNumber(String idNumber) {

  int gender = 0;

  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;
  }

  return gender;

 }
 
 /**
  * 通过身份证获取年龄
  *
  * @param idNumber  身份证号
  * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  * @return 返回年龄
  */
 public static Integer getAgeByIdNumber(String idNumber, boolean isNominalAge) {

  String birthString = getBirthdayByIdNumber(idNumber);
  if (StringHelper.isEmpty(birthString)) {
   return 0;
  }

  return getAgeByBirthString(birthString, isNominalAge);

 }
 
 
 /**
  * 通过生日日期获取年龄
  *
  * @param birthDate 生日日期
  * @return 返回年龄
  */
 public static Integer getAgeByBirthDate(Date birthDate) {

  return getAgeByBirthString(new SimpleDateFormat("yyyy-MM-dd").format(birthDate));

 }
 
 /**
  * 通过生日字符串获取年龄
  *
  * @param birthString 生日字符串
  * @return 返回年龄
  */
 public static Integer getAgeByBirthString(String birthString) {

  return getAgeByBirthString(birthString, "yyyy-MM-dd");

 }

 
 /**
  * 通过生日字符串获取年龄
  *
  * @param birthString 生日字符串
  * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  * @return 返回年龄
  */
 public static Integer getAgeByBirthString(String birthString, boolean isNominalAge) {

  return getAgeByBirthString(birthString, "yyyy-MM-dd", isNominalAge);

 }
 
 /**
  * 通过生日字符串获取年龄
  *
  * @param birthString 生日字符串
  * @param format  日期字符串格式,为空则默认"yyyy-MM-dd"
  * @return 返回年龄
  */
 public static Integer getAgeByBirthString(String birthString, String format) {
  return getAgeByBirthString(birthString, "yyyy-MM-dd", false);
 }
 
 /**
  * 通过生日字符串获取年龄
  *
  * @param birthString 生日字符串
  * @param format  日期字符串格式,为空则默认"yyyy-MM-dd"
  * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
  * @return 返回年龄
  */
 public static Integer getAgeByBirthString(String birthString, String format, boolean isNominalAge) {
  int age = 0;
  if (StringHelper.isEmpty(birthString)) {
   return age;
  }
  if (StringHelper.isEmpty(format)) {
   format = "yyyy-MM-dd";
  }
  try {

   Calendar birthday = Calendar.getInstance();
   Calendar today = Calendar.getInstance();
   SimpleDateFormat sdf = new SimpleDateFormat(format);
   birthday.setTime(sdf.parse(birthString));
   age = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
   if (!isNominalAge) {
    if (today.get(Calendar.MONTH) < birthday.get(Calendar.MONTH) ||
      (today.get(Calendar.MONTH) == birthday.get(Calendar.MONTH) &&
        today.get(Calendar.DAY_OF_MONTH) < birthday.get(Calendar.DAY_OF_MONTH))) {
     age = age - 1;
    }
   }
  } catch (ParseException e) {
   e.printStackTrace();
  }

  return age;

 }
 
 /** 
  * 大小写敏感的正规表达式批配 
  * 
  * @param source 
  *   批配的源字符串 
  * @param regexp 
  *   批配的正规表达式 
  * @return 如果源字符串符合要求返回真,否则返回假 
  */ 
 public static boolean isHardRegexpValidate(String str, String regexp) {
  if (str == null || str.trim().length() == 0) {
 return false;
 }
   Pattern pattern = Pattern.compile(regexp);
  Matcher matcher = pattern.matcher(str);
  return matcher.matches();
 } 
 
}

java常用工具类 UUID、Map工具类

254

本文实例为大家分享了Java常用工具类 的具体代码,供大家参考,具体内容如下

UUID工具类

package com.jarvis.base.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * A class that represents an immutable universally unique identifier (UUID).
 * A UUID represents a 128-bit value.
 * <p/>
 * <p>There exist different variants of these global identifiers. The methods
 * of this class are for manipulating the Leach-Salz variant, although the
 * constructors allow the creation of any variant of UUID (described below).
 * <p/>
 * <p>The layout of a variant 2 (Leach-Salz) UUID is as follows:
 * <p/>
 * The most significant long consists of the following unsigned fields:
 * <pre>
 * 0xFFFFFFFF00000000 time_low
 * 0x00000000FFFF0000 time_mid
 * 0x000000000000F000 version
 * 0x0000000000000FFF time_hi
 * </pre>
 * The least significant long consists of the following unsigned fields:
 * <pre>
 * 0xC000000000000000 variant
 * 0x3FFF000000000000 clock_seq
 * 0x0000FFFFFFFFFFFF node
 * </pre>
 * <p/>
 * <p>The variant field contains a value which identifies the layout of
 * the <tt>UUID</tt>. The bit layout described above is valid only for
 * a <tt>UUID</tt> with a variant value of 2, which indicates the
 * Leach-Salz variant.
 * <p/>
 * <p>The version field holds a value that describes the type of this
 * <tt>UUID</tt>. There are four different basic types of UUIDs: time-based,
 * DCE security, name-based, and randomly generated UUIDs. These types
 * have a version value of 1, 2, 3 and 4, respectively.
 * <p/>
 * <p>For more information including algorithms used to create <tt>UUID</tt>s,
 * see the Internet-Draft <a href="http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-03.txt" rel="external nofollow" >UUIDs and GUIDs</a>
 * or the standards body definition at
 * <a href="http://www.iso.ch/cate/d2229.html" rel="external nofollow" >ISO/IEC 11578:1996</a>.
 *
 * @version 1.14, 07/12/04
 * @since 1.5
 */
@Deprecated
public final class UUID implements java.io.Serializable
{

 /**
  * Explicit serialVersionUID for interoperability.
  */
 private static final long serialVersionUID = -4856846361193249489L;

 /*
  * The most significant 64 bits of this UUID.
  *
  * @serial
  */
 private final long mostSigBits;

 /**
  * The least significant 64 bits of this UUID.
  *
  * @serial
  */
 private final long leastSigBits;

 /*
  * The version number associated with this UUID. Computed on demand.
  */
 private transient int version = -1;

 /*
  * The variant number associated with this UUID. Computed on demand.
  */
 private transient int variant = -1;

 /*
  * The timestamp associated with this UUID. Computed on demand.
  */
 private transient volatile long timestamp = -1;

 /*
  * The clock sequence associated with this UUID. Computed on demand.
  */
 private transient int sequence = -1;

 /*
  * The node number associated with this UUID. Computed on demand.
  */
 private transient long node = -1;

 /*
  * The hashcode of this UUID. Computed on demand.
  */
 private transient int hashCode = -1;

 /*
  * The random number generator used by this class to create random
  * based UUIDs.
  */
 private static volatile SecureRandom numberGenerator = null;

 // Constructors and Factories

 /*
  * Private constructor which uses a byte array to construct the new UUID.
  */
 private UUID(byte[] data)
 {
  long msb = 0;
  long lsb = 0;
  for (int i = 0; i < 8; i++)
   msb = (msb << 8) | (data[i] & 0xff);
  for (int i = 8; i < 16; i++)
   lsb = (lsb << 8) | (data[i] & 0xff);
  this.mostSigBits = msb;
  this.leastSigBits = lsb;
 }

 /**
  * Constructs a new <tt>UUID</tt> using the specified data.
  * <tt>mostSigBits</tt> is used for the most significant 64 bits
  * of the <tt>UUID</tt> and <tt>leastSigBits</tt> becomes the
  * least significant 64 bits of the <tt>UUID</tt>.
  *
  * @param mostSigBits
  * @param leastSigBits
  */
 public UUID(long mostSigBits, long leastSigBits)
 {
  this.mostSigBits = mostSigBits;
  this.leastSigBits = leastSigBits;
 }

 /**
  * Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
  * <p/>
  * The <code>UUID</code> is generated using a cryptographically strong
  * pseudo random number generator.
  *
  * @return a randomly generated <tt>UUID</tt>.
  */
 @SuppressWarnings("unused")
 public static UUID randomUUID()
 {
  SecureRandom ng = numberGenerator;
  if (ng == null)
  {
   numberGenerator = ng = new SecureRandom();
  }

  byte[] randomBytes = new byte[16];
  ng.nextBytes(randomBytes);
  randomBytes[6] &= 0x0f; /* clear version  */
  randomBytes[6] |= 0x40; /* set to version 4  */
  randomBytes[8] &= 0x3f; /* clear variant  */
  randomBytes[8] |= 0x80; /* set to IETF variant */
 UUID result = new UUID(randomBytes);
  return new UUID(randomBytes);
 }

 /**
  * Static factory to retrieve a type 3 (name based) <tt>UUID</tt> based on
  * the specified byte array.
  *
  * @param name a byte array to be used to construct a <tt>UUID</tt>.
  * @return a <tt>UUID</tt> generated from the specified array.
  */
 public static UUID nameUUIDFromBytes(byte[] name)
 {
  MessageDigest md;
  try
  {
   md = MessageDigest.getInstance("MD5");
  }
  catch (NoSuchAlgorithmException nsae)
  {
   throw new InternalError("MD5 not supported");
  }
  byte[] md5Bytes = md.digest(name);
  md5Bytes[6] &= 0x0f; /* clear version  */
  md5Bytes[6] |= 0x30; /* set to version 3  */
  md5Bytes[8] &= 0x3f; /* clear variant  */
  md5Bytes[8] |= 0x80; /* set to IETF variant */
  return new UUID(md5Bytes);
 }

 /**
  * Creates a <tt>UUID</tt> from the string standard representation as
  * described in the {@link #toString} method.
  *
  * @param name a string that specifies a <tt>UUID</tt>.
  * @return a <tt>UUID</tt> with the specified value.
  * @throws IllegalArgumentException if name does not conform to the
  *         string representation as described in {@link #toString}.
  */
 public static UUID fromString(String name)
 {
  String[] components = name.split("-");
  if (components.length != 5)
   throw new IllegalArgumentException("Invalid UUID string: " + name);
  for (int i = 0; i < 5; i++)
   components[i] = "0x" + components[i];

  long mostSigBits = Long.decode(components[0]).longValue();
  mostSigBits <<= 16;
  mostSigBits |= Long.decode(components[1]).longValue();
  mostSigBits <<= 16;
  mostSigBits |= Long.decode(components[2]).longValue();

  long leastSigBits = Long.decode(components[3]).longValue();
  leastSigBits <<= 48;
  leastSigBits |= Long.decode(components[4]).longValue();

  return new UUID(mostSigBits, leastSigBits);
 }

 // Field Accessor Methods

 /**
  * Returns the least significant 64 bits of this UUID's 128 bit value.
  *
  * @return the least significant 64 bits of this UUID's 128 bit value.
  */
 public long getLeastSignificantBits()
 {
  return leastSigBits;
 }

 /**
  * Returns the most significant 64 bits of this UUID's 128 bit value.
  *
  * @return the most significant 64 bits of this UUID's 128 bit value.
  */
 public long getMostSignificantBits()
 {
  return mostSigBits;
 }

 /**
  * The version number associated with this <tt>UUID</tt>. The version
  * number describes how this <tt>UUID</tt> was generated.
  * <p/>
  * The version number has the following meaning:<p>
  * <ul>
  * <li>1 Time-based UUID
  * <li>2 DCE security UUID
  * <li>3 Name-based UUID
  * <li>4 Randomly generated UUID
  * </ul>
  *
  * @return the version number of this <tt>UUID</tt>.
  */
 public int version()
 {
  if (version < 0)
  {
   // Version is bits masked by 0x000000000000F000 in MS long
   version = (int) ((mostSigBits >> 12) & 0x0f);
  }
  return version;
 }

 /**
  * The variant number associated with this <tt>UUID</tt>. The variant
  * number describes the layout of the <tt>UUID</tt>.
  * <p/>
  * The variant number has the following meaning:<p>
  * <ul>
  * <li>0 Reserved for NCS backward compatibility
  * <li>2 The Leach-Salz variant (used by this class)
  * <li>6 Reserved, Microsoft Corporation backward compatibility
  * <li>7 Reserved for future definition
  * </ul>
  *
  * @return the variant number of this <tt>UUID</tt>.
  */
 public int variant()
 {
  if (variant < 0)
  {
   // This field is composed of a varying number of bits
   if ((leastSigBits >>> 63) == 0)
   {
    variant = 0;
   }
   else if ((leastSigBits >>> 62) == 2)
   {
    variant = 2;
   }
   else
   {
    variant = (int) (leastSigBits >>> 61);
   }
  }
  return variant;
 }

 /**
  * The timestamp value associated with this UUID.
  * <p/>
  * <p>The 60 bit timestamp value is constructed from the time_low,
  * time_mid, and time_hi fields of this <tt>UUID</tt>. The resulting
  * timestamp is measured in 100-nanosecond units since midnight,
  * October 15, 1582 UTC.<p>
  * <p/>
  * The timestamp value is only meaningful in a time-based UUID, which
  * has version type 1. If this <tt>UUID</tt> is not a time-based UUID then
  * this method throws UnsupportedOperationException.
  *
  * @throws UnsupportedOperationException if this UUID is not a
  *          version 1 UUID.
  */
 public long timestamp()
 {
  if (version() != 1)
  {
   throw new UnsupportedOperationException("Not a time-based UUID");
  }
  long result = timestamp;
  if (result < 0)
  {
   result = (mostSigBits & 0x0000000000000FFFL) << 48;
   result |= ((mostSigBits >> 16) & 0xFFFFL) << 32;
   result |= mostSigBits >>> 32;
   timestamp = result;
  }
  return result;
 }

 /**
  * The clock sequence value associated with this UUID.
  * <p/>
  * <p>The 14 bit clock sequence value is constructed from the clock
  * sequence field of this UUID. The clock sequence field is used to
  * guarantee temporal uniqueness in a time-based UUID.<p>
  * <p/>
  * The clockSequence value is only meaningful in a time-based UUID, which
  * has version type 1. If this UUID is not a time-based UUID then
  * this method throws UnsupportedOperationException.
  *
  * @return the clock sequence of this <tt>UUID</tt>.
  * @throws UnsupportedOperationException if this UUID is not a
  *          version 1 UUID.
  */
 public int clockSequence()
 {
  if (version() != 1)
  {
   throw new UnsupportedOperationException("Not a time-based UUID");
  }
  if (sequence < 0)
  {
   sequence = (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
  }
  return sequence;
 }

 /**
  * The node value associated with this UUID.
  * <p/>
  * <p>The 48 bit node value is constructed from the node field of
  * this UUID. This field is intended to hold the IEEE 802 address
  * of the machine that generated this UUID to guarantee spatial
  * uniqueness.<p>
  * <p/>
  * The node value is only meaningful in a time-based UUID, which
  * has version type 1. If this UUID is not a time-based UUID then
  * this method throws UnsupportedOperationException.
  *
  * @return the node value of this <tt>UUID</tt>.
  * @throws UnsupportedOperationException if this UUID is not a
  *          version 1 UUID.
  */
 public long node()
 {
  if (version() != 1)
  {
   throw new UnsupportedOperationException("Not a time-based UUID");
  }
  if (node < 0)
  {
   node = leastSigBits & 0x0000FFFFFFFFFFFFL;
  }
  return node;
 }

 // Object Inherited Methods

 /**
  * Returns a <code>String</code> object representing this
  * <code>UUID</code>.
  * <p/>
  * <p>The UUID string representation is as described by this BNF :
  * <pre>
  * UUID     = <time_low> "-" <time_mid> "-"
  *       <time_high_and_version> "-"
  *       <variant_and_sequence> "-"
  *       <node>
  * time_low    = 4*<hexOctet>
  * time_mid    = 2*<hexOctet>
  * time_high_and_version = 2*<hexOctet>
  * variant_and_sequence = 2*<hexOctet>
  * node     = 6*<hexOctet>
  * hexOctet    = <hexDigit><hexDigit>
  * hexDigit    =
  *  "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
  *  | "a" | "b" | "c" | "d" | "e" | "f"
  *  | "A" | "B" | "C" | "D" | "E" | "F"
  * </pre>
  *
  * @return a string representation of this <tt>UUID</tt>.
  */
 public String toString()
 {
  return (digits(mostSigBits >> 32, 8) + "-" +
    digits(mostSigBits >> 16, 4) + "-" +
    digits(mostSigBits, 4) + "-" +
    digits(leastSigBits >> 48, 4) + "-" +
    digits(leastSigBits, 12));
 }

 /**
  * Returns val represented by the specified number of hex digits.
  */
 private static String digits(long val, int digits)
 {
  long hi = 1L << (digits * 4);
  return Long.toHexString(hi | (val & (hi - 1))).substring(1);
 }

 /**
  * Returns a hash code for this <code>UUID</code>.
  *
  * @return a hash code value for this <tt>UUID</tt>.
  */
 public int hashCode()
 {
  if (hashCode == -1)
  {
   hashCode = (int) ((mostSigBits >> 32) ^
     mostSigBits ^
     (leastSigBits >> 32) ^
     leastSigBits);
  }
  return hashCode;
 }

 /**
  * Compares this object to the specified object. The result is
  * <tt>true</tt> if and only if the argument is not
  * <tt>null</tt>, is a <tt>UUID</tt> object, has the same variant,
  * and contains the same value, bit for bit, as this <tt>UUID</tt>.
  *
  * @param obj the object to compare with.
  * @return <code>true</code> if the objects are the same;
  *   <code>false</code> otherwise.
  */
 public boolean equals(Object obj)
 {
  if (!(obj instanceof UUID))
   return false;
  if (((UUID) obj).variant() != this.variant())
   return false;
  UUID id = (UUID) obj;
  return (mostSigBits == id.mostSigBits &&
    leastSigBits == id.leastSigBits);
 }

 // Comparison Operations

 /**
  * Compares this UUID with the specified UUID.
  * <p/>
  * <p>The first of two UUIDs follows the second if the most significant
  * field in which the UUIDs differ is greater for the first UUID.
  *
  * @param val <tt>UUID</tt> to which this <tt>UUID</tt> is to be compared.
  * @return -1, 0 or 1 as this <tt>UUID</tt> is less than, equal
  *   to, or greater than <tt>val</tt>.
  */
 public int compareTo(UUID val)
 {
  // The ordering is intentionally set up so that the UUIDs
  // can simply be numerically compared as two numbers
  return (this.mostSigBits < val.mostSigBits ? -1 :
    (this.mostSigBits > val.mostSigBits ? 1 :
      (this.leastSigBits < val.leastSigBits ? -1 :
        (this.leastSigBits > val.leastSigBits ? 1 :
          0))));
 }

 /**
  * Reconstitute the <tt>UUID</tt> instance from a stream (that is,
  * deserialize it). This is necessary to set the transient fields
  * to their correct uninitialized value so they will be recomputed
  * on demand.
  */
 private void readObject(java.io.ObjectInputStream in)
   throws java.io.IOException, ClassNotFoundException
 {

  in.defaultReadObject();

  // Set "cached computation" fields to their initial values
  version = -1;
  variant = -1;
  timestamp = -1;
  sequence = -1;
  node = -1;
  hashCode = -1;
 }
 
}

Map工具类

package com.jarvis.base.util;

import java.util.Map;
/**
 * 
 * 
 * @Title: MapHelper.java
 * @Package com.jarvis.base.util
 * @Description:Map工具类
 * @version V1.0 
 */
public class MapHelper {
 /**
 * 获得字串值
 *
 * @param name
 *   键值名称
 * @return 若不存在,则返回空字串
 */
 public static String getString(Map<?, ?> map, String name) {
 if (name == null || name.equals("")) {
 return "";
 }

 String value = "";
 if (map.containsKey(name) == false) {
 return "";
 }
 Object obj = map.get(name);
 if (obj != null) {
 value = obj.toString();
 }
 obj = null;

 return value;
 }

 /**
 * 返回整型值
 *
 * @param name
 *   键值名称
 * @return 若不存在,或转换失败,则返回0
 */
 public static int getInt(Map<?, ?> map, String name) {
 if (name == null || name.equals("")) {
 return 0;
 }

 int value = 0;
 if (map.containsKey(name) == false) {
 return 0;
 }

 Object obj = map.get(name);
 if (obj == null) {
 return 0;
 }

 if (!(obj instanceof Integer)) {
 try {
 value = Integer.parseInt(obj.toString());
 } catch (Exception ex) {
 ex.printStackTrace();
 System.err.println("name[" + name + "]对应的值不是数字,返回0");
 value = 0;
 }
 } else {
 value = ((Integer) obj).intValue();
 obj = null;
 }

 return value;
 }

 /**
 * 获取长整型值
 *
 * @param name
 *   键值名称
 * @return 若不存在,或转换失败,则返回0
 */
 public static long getLong(Map<?, ?> map, String name) {
 if (name == null || name.equals("")) {
 return 0;
 }

 long value = 0;
 if (map.containsKey(name) == false) {
 return 0;
 }

 Object obj = map.get(name);
 if (obj == null) {
 return 0;
 }

 if (!(obj instanceof Long)) {
 try {
 value = Long.parseLong(obj.toString());
 } catch (Exception ex) {
 ex.printStackTrace();
 System.err.println("name[" + name + "]对应的值不是数字,返回0");
 value = 0;
 }
 } else {
 value = ((Long) obj).longValue();
 obj = null;
 }

 return value;
 }

 /**
 * 获取Float型值
 *
 * @param name
 *   键值名称
 * @return 若不存在,或转换失败,则返回0
 */
 public static float getFloat(Map<?, ?> map, String name) {
 if (name == null || name.equals("")) {
 return 0;
 }

 float value = 0;
 if (map.containsKey(name) == false) {
 return 0;
 }

 Object obj = map.get(name);
 if (obj == null) {
 return 0;
 }

 if (!(obj instanceof Float)) {
 try {
 value = Float.parseFloat(obj.toString());
 } catch (Exception ex) {
 ex.printStackTrace();
 System.err.println("name[" + name + "]对应的值不是数字,返回0");
 value = 0;
 }
 } else {
 value = ((Float) obj).floatValue();
 obj = null;
 }

 return value;
 }

 /**
 * 获取Double型值
 *
 * @param name
 *   键值名称
 * @return 若不存在,或转换失败,则返回0
 */
 public static double getDouble(Map<?, ?> map, String name) {
 if (name == null || name.equals("")) {
 return 0;
 }

 double value = 0;
 if (map.containsKey(name) == false) {
 return 0;
 }

 Object obj = map.get(name);
 if (obj == null) {
 return 0;
 }

 if (!(obj instanceof Double)) {
 try {
 value = Double.parseDouble(obj.toString());
 } catch (Exception ex) {
 ex.printStackTrace();
 System.err.println("name[" + name + "]对应的值不是数字,返回0");
 value = 0;
 }
 } else {
 value = ((Double) obj).doubleValue();
 obj = null;
 }

 return value;
 }

 /**
 * 获取Bool值
 *
 * @param name
 *   键值名称
 * @return 若不存在,或转换失败,则返回false
 */
 public static boolean getBoolean(Map<?, ?> map, String name) {
 if (name == null || name.equals("")) {
 return false;
 }

 boolean value = false;
 if (map.containsKey(name) == false) {
 return false;
 }
 Object obj = map.get(name);
 if (obj == null) {
 return false;
 }

 if (obj instanceof Boolean) {
 return ((Boolean) obj).booleanValue();
 }

 value = Boolean.valueOf(obj.toString()).booleanValue();
 obj = null;
 return value;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持码农之家。


参考资料

相关文章

  • Java继承概念知识点分享

    发布:2019-09-10

    这篇文章主要介绍了Java继承概念详细解读,涉及继承的概念,合成的语法等相关内容,具有一定借鉴价值,需要的朋友可以参考下。


  • 实例解析Java Chaos Game噪声游戏

    发布:2020-03-06

    这篇文章主要介绍了Java Chaos Game噪声游戏实例代码,具有一定借鉴价值,需要的朋友可以参考下。


  • java8中:: 用法示例(JDK8双冒号用法)

    发布:2022-09-13

    给大家整理了关于java8的教程,这篇文章主要给大家介绍了关于java8 中的:: 用法(JDK8双冒号用法)的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用java8具有一定的参考学习价值,需要的朋友们下面来一起


  • 关于java网络编程基础

    发布:2020-02-28

    这篇文章主要介绍了java网络编程基础知识介绍,涉及OSI分层模型和TCP/IP分层模型的对应关系、IP地址、端口号、tcp、udp等相关内容,还是比较不错的,这里分享给大家,供需要的朋友参考。


  • JavaScript String 对象常用实例方法

    发布:2020-04-06

    下面小编就为大家带来一篇JavaScript String 对象常用方法详解。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧


  • Java微服务Nacos Config配置中心超详细讲解

    发布:2023-04-09

    配置文件相对分散。在一个微服务架构下,配置文件会随着微服务的增多变的越来越多,而且分散 在各个微服务中,不好统一配置和管理。每一个环境所使用的配置理论上都是不同的,一旦需要修改,就需要我们去各个微服务下手动维护


  • Java通过BCrypt加密的具体方法和步骤

    发布:2020-01-16

    这篇文章主要介绍了Java通过BCrypt加密过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下


  • Java覆盖finalize()方法代码实例讲解

    发布:2019-06-04

    这篇文章主要介绍了Java中覆盖finalize()方法实例代码,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下


网友讨论