Java開發中日常操作轉化工具類
package com.util;import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.NetworkInterface; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class Util { /** * ERRORTYPE */ public static final String ERRORTYPE = "TYPE"; /** * ERRORTYPE_ERROR */ public static final String ERRORTYPE_ERROR = "ERROR"; /** * ERRORCODE */ public static final String ERRORCODE = "ERRORCODE"; /** * ERRORINFO */ public static final String ERRORINFO = "ERRORINFO"; /** * GOPAGE */ public static final String GOPAGE = "GOPAGE"; /** * 有效小數 */ public static final int EFFECTIVE = 2; protected static final Log LOG = LogFactory.getLog(Util.class); /** * 移除重復 * * @param arr * 要處理的字符串數 * @return 處理后的字符串數 */ public static String[] removeRepeat(String[] arr) { if (arr == null) { return new String[0]; } else { Map<String, String> map = new HashMap<String, String>(); for (String str : arr) { String strt = map.get(str); if (strt == null) { map.put(str, str); } } List<String> list = new ArrayList<String>(); for (Map.Entry<String, String> entry : map.entrySet()) { list.add(entry.getKey()); } String[] strArr = new String[list.size()]; return list.toArray(strArr); } } /** * 移除重復 * */ public static String removeRepeat(String str) { if (str == null) { return ""; } else { str = str.replaceAll("^,+", ""); str = str.replaceAll(",+$", ""); str = str.replaceAll(",+", ","); StringBuffer buf = new StringBuffer(); for (String strt : removeRepeat(str.split(","))) { buf.append(strt).append(','); } str = removeEnd(buf.toString()); return str; } } /** * 移除開頭的逗號 * */ public static String removeBegin(String str) { if (str == null) { return ""; } else { Matcher matcher = Pattern.compile("^,+").matcher(str); str = matcher.replaceAll(""); return str; } } /** * 移除結尾的逗號 * */ public static String removeEnd(String str) { if (str == null) { return ""; } else { Matcher matcher = Pattern.compile(",+$").matcher(str); str = matcher.replaceAll(""); return str; } } /** * 格式化日期 * @param date 日期 * @param pattern 格式 * @return String String */ public static String formatDate(Date date, String pattern) { SimpleDateFormat format = new SimpleDateFormat(pattern); return format.format(date); } /** * 〈計算兩個日期相差的天數〉 * 〈功能詳細描述〉 * @param begin 開始日期 * @param end 結束日期 * @return long */ public static long calDays(Date begin, Date end) { long time = end.getTime() - begin.getTime(); long days = time / 24 / 60 / 60 / 1000; return days; } /** * 獲取未來第幾天的時間yyyy-MM-dd * @param dayNum * @return */ public static String getNextDay(int dayNum){ Calendar cal = Calendar.getInstance(); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String returnDate =""; try { cal.setTime(date); cal.add(Calendar.DATE, dayNum); returnDate = sdf.format(cal.getTime()); } catch (Exception e) { e.printStackTrace(); } return returnDate; } /** * 格式化日期 * @param str 日期字符串 * @param pattern 格式 * @return Date Date */ public static Date formatDate(String str, String pattern) { Date date = null; try { SimpleDateFormat format = new SimpleDateFormat(pattern); date = format.parse(str); } catch (ParseException e) { date = new Date(); } return date; } /** * 解析字符 * * @param key * key * @param str * str * @return value */ public static String getValue(String key, String str) { if (key == null || str == null) { return ""; } String[] strArr = str.split(","); for (String tempStr : strArr) { if (key.equals(tempStr.split(":")[0])) { return tempStr.split(":")[1]; } } return ""; } /** * 解析字符 * * @param key * key * @param str * str * @return value */ public static int getIntValue(String key, String str) { int result = 0; if (str == null) { return result; } String[] strArr = str.split(","); String value = "0"; for (String tempStr : strArr) { if (key.equals(tempStr.split(":")[0])) { value = tempStr.split(":")[1]; } } try { result = Integer.parseInt(value); } catch (Exception e) { result = 0; } return result; } /** * 解析字符 */ public static String[] getValue(String str) { if (str == null) { return new String[0]; } return str.split(","); } /** * 直接向用戶返回指定信息 * * @param response * response * @param msg * void */ public static void returnMsg(HttpServletResponse response, String msg) { Writer out = null; try { out = response.getWriter(); out.write(msg); out.close(); } catch (IOException e) { LOG.error(e); } } /** * * @param str str * @param reg reg * @param newValue newValue * @return String */ public static String replace(String str, String reg, String newValue) { if (!isEmpty(str)) { Matcher matcher = Pattern.compile(reg, Pattern.CASE_INSENSITIVE).matcher(str); str = matcher.replaceAll(newValue); } return str; } /** * * @param str str * @param reg reg * @param newValue newValue * @param param param * @return String */ public static String replace(String str, String reg, String newValue, int param) { if (!isEmpty(str)) { Matcher matcher = Pattern.compile(reg, param).matcher(str); str = matcher.replaceAll(newValue); } return str; } /** * 〈移除字符串中的js代碼 * * @param str * str * @return String */ public static String removeScript(String str) { if (str == null || "".equals(str)) { return ""; } int param = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL; Matcher matcher = Pattern.compile("<script>.*</script>", param).matcher(str); str = matcher.replaceAll(""); return str; } /** * 字符串轉成整數 * * @param str * 字符 * @return 數字 */ public static int parseInt(String str) { int result = 0; try { result = Integer.parseInt(str); } catch (Exception e) { result = 0; } return result; } /** * 〈文件重命名〉 * * @param realPath * 文件絕對路徑 * @param newName * 新文件名 * @return String */ public static String rename(String realPath, String newName) { File file = new File(realPath); //包含后綴的文件名 String fileName = file.getName(); //不包含后的文件名 String name = fileName.substring(0, fileName.lastIndexOf('.')); //帶后的新文件名稱 newName = fileName.replace(name, newName); realPath = realPath.replace(fileName, newName); if (file.exists()) { try { if (!file.renameTo(new File(realPath))) { throw new Exception(); } } catch (Exception e) { e.printStackTrace(); } } return newName; } /** * 把數組轉換成字符串,并以逗號分隔 * * @param arr * arr * @return 轉換結果 */ public static String arrayToString(String[] arr) { if (arr == null) { return ""; } StringBuffer buf = new StringBuffer(); for (String str : arr) { if (str != null && !"".equals(str)) { buf.append(str).append(','); } } String result = buf.toString(); result = result.replaceAll(",$", ""); return result; } /** * 寫Excel * * @param response * response * @param file * file */ public static void writeExcel(HttpServletResponse response, File file) { if (file != null && file.exists()) { response.reset(); response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); InputStream inStream = null; try { inStream = new FileInputStream(file); int len = inStream.read(); while (len != -1) { response.getWriter().write(len); len = inStream.read(); } } catch (Exception e) { e.printStackTrace(); } finally { Util.close(inStream); } } } /** * * @param reg * reg * @param str * str * @return boolean */ public static boolean test(String reg, String str) { Matcher matcher = Pattern.compile(reg).matcher(str); return matcher.find(); } /** *關閉流 * @param ins void */ public static void close(InputStream ins) { if (ins != null) { try { ins.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 關閉流 * @param ous void */ public static void close(OutputStream ous) { if (ous != null) { try { ous.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * * 〈重新組裝查詢條件〉 * 〈如果查詢條件包含"_"就在"_"之前加上轉義字符"/"〉 * @param queryCondition 查詢條件 * @return String */ public static String resetCondition(String queryCondition) { char[] temps = queryCondition.toCharArray(); //查詢條件 StringBuffer condition = new StringBuffer(); //重新組裝查詢條件的字符串,如果包"_"就在"_"之前加上轉義字符"/" for (char temp : temps) { if ('_' == temp) { condition.append('/').append(temp); } else { condition.append(temp); } } return condition.toString(); } /** *〈驗證字符串是否為空〉 * @param str str * @return boolean */ public static boolean isEmpty(String str) { return str == null || "".equals(str); } /** *〈驗證字符串是否不為空〉 * @param str str * @return boolean */ public static boolean notEmpty(String str) { return !isEmpty(str); } /** *〈驗證字符串是否為空〉 * @param str str * @return boolean */ public static boolean isEmpty(Object str) { return str == null; } /** *〈〈驗證字符串是否為空〉 * @param list list * @return boolean */ public static boolean isEmpty(List<?> list) { return list == null || list.isEmpty(); } /** *〈〈驗證字符串是否不為空〉 * @param list list * @return boolean */ public static boolean notEmpty(List<?> list) { return !isEmpty(list); } /** *〈驗證字符串是否為空〉 * @param map 待處理的集合 * @return boolean */ public static boolean isEmpty(Map<?, ?> map) { return map == null || map.isEmpty(); } /** *〈驗證字符串是否不為空〉 * @param map 待處理的集合 * @return boolean */ public static boolean notEmpty(Map<?, ?> map) { return !isEmpty(map); } /** *〈轉換為小寫 * @param str str * @return String */ public static String lowerCase(String str) { if (str != null) { str = str.toLowerCase(Locale.CHINESE); } return str; } /** *〈轉換為大寫〉 * @param str str * @return String */ public static String upperCase(String str) { if (str != null) { str = str.toUpperCase(Locale.CHINESE); } return str; } /** *〈一句話功能描述〉 * @param cls cls * @param methodName methodName * @param classArr classArr * @return Method */ @SuppressWarnings("unchecked") public static Method getMethod(Class<?> cls, String methodName, Class[] classArr) { Method mtd = null; try { mtd = cls.getDeclaredMethod(methodName, classArr); } catch (SecurityException e) { LOG.error(e); } catch (NoSuchMethodException e) { LOG.error(e); } return mtd; } /** * 獲取當前服務器ip * @return String */ public static String getLocalSiteIP() { String siteString = ""; try { Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); NetworkInterface networkInterface = null; InetAddress ipAddress = null; while (netInterfaces.hasMoreElements()) { networkInterface = (NetworkInterface)netInterfaces.nextElement(); ipAddress = (InetAddress)networkInterface.getInetAddresses().nextElement(); if (ipAddress.isSiteLocalAddress() && !ipAddress.isLoopbackAddress() && ipAddress.getHostAddress().indexOf(":") == -1) { siteString = ipAddress.getHostAddress(); } } } catch (Exception e) { e.toString(); } return siteString; } /** * 〈trim公共方法 * 〈功能詳細描述 * @param str str * @return String */ public static String trim(String str) { if (str != null) { str = str.trim(); } return str; } /** * 檢查算法表達式合法性 * @param calculateScript 計算腳本 * @return 返回true表達式合?,false表達式不合法 */ public static boolean checkCalculateScript(String calculateScript) { return true; } /** * 獲取系統時間 * @return 當前系統時間 */ public static Date getSysDate() { SimpleDateFormat ft = null; Calendar cal = Calendar.getInstance(); // 格式可以自己根據要求修改 ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateTime = ft.format(cal.getTime()); Date nowDate = null; try { nowDate = ft.parse(dateTime); } catch (ParseException e) { LOG.error(e); // e.printStackTrace(); } return nowDate; } /** * 〈根據系統當前時間獲取下一個月日期對象〉 * 〈功能詳細描述〉 * @return Date */ public static Date getNextMonth() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 1); return cal.getTime(); } /** * 設置文件輸出流的文件名 * @param failName 文件名 * @param response void */ public static void responseSetHeader(String failName, HttpServletResponse response) { response.setHeader("Content-disposition", "attachment; filename=" + failName); response.setContentType("application/msexcel"); } /** *〈為空驗證〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean empty(String str, String prop) { if (str == null) { return false; } if ("".equals(str.trim())) { return false; } return true; } /* *〈按字節驗證字符串長度〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ /* public static boolean byteLength(String str, String prop) { int length = 20; if (Util.isEmpty(str)) { return true; } char[] chars = str.toCharArray(); int len = 0; for (int i = 0; i < chars.length; i++) { len++; //判斷是否非字母 if (chars[i] / 0x80 == 0) { len++; } } return len <= length; }*/ /** *〈非法字符〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean lawless(String str) { boolean result = false; if (Util.isEmpty(str)) { result = true; } result = !Util.test("^[-~!@#$%^&*()_+|=\\;':\",./<>?]+$", str); return result; } /** *〈驗證只能為漢字〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean chinese(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^[\u4E00-\u9FA5]+$", str); } /** *〈驗證只能為字母〉 * @param str 待驗證字符串 * @return boolean */ protected static boolean letter(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^[a-zA-Z]+$", str); } /** *〈驗證數字是否在指定范圍〉 * @param str str * @param prop prop * @return boolean */ protected static boolean number(String str) { return true; } /** *〈驗證手機號碼〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean mobile(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^1\\d{10}$", str); } /** *〈驗證IP〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean checkIP(String str) { if (Util.isEmpty(str)) { return true; } String pattern = "^(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])(\\.(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])){3}$"; return Util.test(pattern, str); } /** *〈驗證日期〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean date(String str) { String pattern = ""; if (Util.isEmpty(str)) { return true; } SimpleDateFormat format = new SimpleDateFormat(pattern); try { format.parse(str); } catch (ParseException e) { return false; } return true; } /** *〈驗證郵編〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean postalCode(String str) { if (Util.isEmpty(str)) { return true; } //暫未實現 return true; } /** *〈驗證EMAIL〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean email(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^[a-zA-Z0-9_.]+@\\w+\\-?\\w+(\\.\\w+)$", str); } /* *〈驗證身份證〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ /* public static boolean checkID(String str) { if (Util.isEmpty(str)) { return true; } if (Util.test("^\\d{17}[xX\\d]$", str)) { return checkID18(str); } else if (Util.test("^\\d{15}$", str)) { return checkID15(str); } else { return false; } }*/ /*private static boolean checkID18(String str) { String year = str.substring(6, 2); String month = str.substring(8, 2); String day = str.substring(10, 2); if (!Util.test("^\\d\\d$", year)) { return false; } if (!isMonth(month)) { return false; } if (!isDay(day)) { return false; } if (Util.parseInt(month) == 2 && Util.parseInt(day) > FEB_DAYES) { return false; } return true; } private static boolean checkID15(String str) { String year = str.substring(ID15_YEAR, 4); String month = str.substring(ID15_MONTH, 2); String day = str.substring(ID15_DAY, 2); if (!isYear(year)) { return false; } if (!isMonth(month)) { return false; } if (!isDay(day)) { return false; } if (Util.parseInt(month) == 2 && Util.parseInt(day) > FEB_DAYES) { return false; } return true; }*/ /** *〈驗證必須為數字〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean mustNum(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^\\d+$", str); } /** *〈體重驗證〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean avoirdupois(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^([3-9]\\d|1\\d\\d)(\\.\\d{0,2})?$", str); } /** *〈驗證身高〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean stature(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^([89]\\d|[12]\\d\\d)(\\.\\d{0,2})?$", str); } /** *〈驗證年齡〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean age(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^([1-9]|[1-9]\\d?)$", str); } /** *〈驗證鞋碼〉 * @param str 待驗證字符串 * @param prop prop * @return boolean */ protected static boolean shoeSize(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("(^[34]\\d$)|(^50$)", str); } /** * 判斷是否為數字,包含浮點型 * @param str * @return */ public static boolean checkNum(String str) { if (Util.isEmpty(str)) { return true; } return Util.test("^\\d+(\\.\\d+){0,1}$", str); } public static void main(String[] args) { System.out.println(checkNum("12")); } } </pre><br />
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!