本文实例为大家分享了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;
public final class XMLHelper {
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;
}
}
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;
}
}
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);
}
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;
}
}
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;
}
}
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;
}
}
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;
}
}
public static String getString(String name, Element element) {
return (element.valueOf(name) == null) ? "" : element.valueOf(name);
}
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;
}
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}$");
public static final String ICON_REGEXP = "^(/{0,1}//w){1,}//.(gif|dmp|png|jpg)$|^//w{1,}//.(gif|dmp|png|jpg)$";
public static final String EMAIL_REGEXP = "(?://w[-._//w]*//w@//w[-._//w]*//w//.//w{2,3}$)";
public static final String URL_REGEXP = "(//w+)://([^/:]+)(://d*)?([^#//s]*)";
public static final String HTTP_REGEXP = "(http|https|ftp)://([^/:]+)(://d*)?([^#//s]*)";
public static final String DATE_BARS_REGEXP = "^((((19){1}|(20){1})\d{2})|\d{2})-[0,1]?\d{1}-[0-3]?\d{1}$";
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)))$";
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}$";
public static final String ID_CARD_REGEXP = "^//d{10}|//d{13}|//d{15}|//d{18}$";
public static final String ZIP_REGEXP = "^[0-9]{6}$";// 匹配邮编代码
public static final String NON_SPECIAL_CHAR_REGEXP = "^[^'/";
// 匹配邮编代码
public static final String NON_NEGATIVE_INTEGERS_REGEXP = "^//d+$";
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]*$";
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+$";
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]*))$";
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+)?$";
public static final String LETTER_REGEXP = "^[A-Za-z]+$";
public static final String UPWARD_LETTER_REGEXP = "^[A-Z]+$";
public static final String LOWER_LETTER_REGEXP = "^[a-z]+$";
public static final String LETTER_NUMBER_REGEXP = "^[A-Za-z0-9]+$";
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();
}
public static boolean validateCode(String code) {
if (StringHelper.isEmpty(code)) {
return false;
}
Matcher m = CODE_PATTERN.matcher(code);
return m.matches();
}
public static boolean validatePostcode(String postcode) {
if (StringHelper.isEmpty(postcode)) {
return false;
}
Matcher m = POSTCODE_PATTERN.matcher(postcode);
return m.matches();
}
public static boolean validateBankCardNumber(String bankCardNumber) {
if (StringHelper.isEmpty(bankCardNumber)) {
return false;
}
Matcher m = BANK_CARD_PATTERN.matcher(bankCardNumber);
return m.matches();
}
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;
}
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;
}
public static Integer getAgeByIdNumber(String idNumber, boolean isNominalAge) {
String birthString = getBirthdayByIdNumber(idNumber);
if (StringHelper.isEmpty(birthString)) {
return 0;
}
return getAgeByBirthString(birthString, isNominalAge);
}
public static Integer getAgeByBirthDate(Date birthDate) {
return getAgeByBirthString(new SimpleDateFormat("yyyy-MM-dd").format(birthDate));
}
public static Integer getAgeByBirthString(String birthString) {
return getAgeByBirthString(birthString, "yyyy-MM-dd");
}
public static Integer getAgeByBirthString(String birthString, boolean isNominalAge) {
return getAgeByBirthString(birthString, "yyyy-MM-dd", isNominalAge);
}
public static Integer getAgeByBirthString(String birthString, String format) {
return getAgeByBirthString(birthString, "yyyy-MM-dd", false);
}
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;
}
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();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



