您好,登錄后才能下訂單哦!
本文實例為大家分享了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(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。