当前位置: 移动技术网 > IT编程>开发语言>Java > java常用工具类 XML工具类、数据验证工具类

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了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/?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();
 } 
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网