标签:
<pre name="code" class="html">public class Tools { private static final String regex = "[a-zA-Z0-9][a-zA-Z0-9_\\.\\-]*[a-zA-Z0-9]@([a-zA-Z0-9_\\-]+[\\.]){1,}[a-zA-Z0-9_\\-]+"; public static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String mobileRegExp = "^[1][0-9]{10}$"; /** * 获取随机数 * * @return int */ public static int getRandom() { return (int) (Math.random() * 98) + 1; } /** * 随机6位数字 * * @return */ public static String getRandomString() { Random random = new Random(); String str = ""; for (int i = 0; i < 6; i++) { str = str + random.nextInt(10); } return str; } /** * 睡眠时间 * * @param i * int 秒为单位 */ public static void sleep(int i) { try { TimeUnit.SECONDS.sleep(i); } catch (InterruptedException e) { } } /** * 是不是Email * * @param input * 需要验证的字符串 * @return 是 true; 否 false */ public static boolean isEmail(String input) { if (null != input) { return Pattern.matches(regex, input); } else { return false; } } /** * 获取工程的WebRoot路径 * * @param request * @return String 例如:F:\project\WebRoot * * public static String getWebRoot(HttpServletRequest request) { * return request.getSession().getServletContext().getRealPath(""); * } */ /** * 获取工程的WebRoot路径 * * @param request * @return String 例如:F:\project\WebRoot */ public static String getWebRoot() { String root = System.getProperty("web.root"); if (root.endsWith("\\")) { root = root.substring(0, root.length() - 1); } return root; } public static String getMavenWebRoot(){ String root = Tools.class.getClassLoader().getResource("/").getPath().replace("/target/classes", "/src/main/webapp"); root = root.substring(1); return root; } /** * 判断是为空或空字符串 * * @param value * @return */ public static boolean isEmpty(String value) { return (value == null) || (value.trim().equals("")); } /** * 获取classes目录路径 如:F:/email3/WebRoot/WEB-INF/classes/ * * @return */ public static String getClassPath() { String classPath = Tools.class.getResource("/").getPath().substring(1); if (classPath.startsWith("/")) { classPath = classPath.substring(1); } return classPath; } /** * 获取classes目录下相对路径的文件流 如:/config/email-config.xml * * @return */ public static InputStream getClassPathFile(String relativePath) { InputStream in = Tools.class.getClass().getResourceAsStream(relativePath); return in; } public static String getFormatDate(Date date, String format) { return new SimpleDateFormat(format).format(date); } public static String getSimpleDate(Date date) { return getFormatDate(date, FORMAT); } public static String getDefaultDate() { return getSimpleDate(new Date()); } /** * 获取指点的当前格式化时间 * * @param format * 例如(yyyy-MM-dd HH:mm:ss) * @return String */ public static String getCurrentDateFormat(String format) { SimpleDateFormat sf = new SimpleDateFormat(format); return sf.format(new Date()); } /** * 获取uuid * * @return */ public static String getUUID() { return UUID.randomUUID().toString().replace("-", ""); } /** * 获取工程的WebRoot路径 * * @param request * @return String 例如:D:\soft_path\Tomcat6.0.29\webapps\microblog */ public static String getRootPath(HttpServletRequest request) { return request.getSession().getServletContext().getRealPath("/"); } public static String toTrim(String value) { if (isEmpty(value)) { return ""; } return value.trim(); } public static int toInt(String s, int i) { if (Validate.isNumber(s)) { return Integer.parseInt(s); } return i; } public static double toDouble(String s, double i) { if (Validate.isNumber(s) || Validate.isFloat(s)) { return Double.parseDouble(s); } return i; } /** * MD5加密 * * @param s * @return */ public final static String MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 过滤html文件 * * @param word * @return */ public static String filterHTML(String word) { if (null == word) { return ""; } else { // return word.trim().replace("&", "&").replace("<", "<").replace(">", ">"); } } /** * 过滤所有html的标签 * * @param html * @return */ public static String removeHtml(String html) { if (html == null) { return ""; } else { char[] words = html.toCharArray(); StringBuffer sbf = new StringBuffer(); int i = 0; boolean flag = true; while (i < words.length) { if (flag && words[i] == '<') { flag = false; } else if (!flag && words[i] == '>') { flag = true; } else if (flag) { sbf.append(words[i]); } i++; } return sbf.toString(); } } /** * 获取请求的url完整地址 * * @param request * @return */ public static String getRequestURL(HttpServletRequest request) { String queryString = request.getQueryString(); queryString = queryString == null ? "" : queryString.trim(); try { queryString = URLEncoder.encode(queryString, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } queryString = "".equals(queryString) ? "" : "?" + queryString; return request.getRequestURL() + queryString; } public static String toUTF8(String str) { if (null == str || "".equals(str)) { return ""; } try { str = URLEncoder.encode(str, "utf-8"); return str; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } /** * * @param array * 字符数组 * @param regex * 分隔符 * @return */ public static String arrayToString(String[] array, String regex) { String returnString = ""; if (array == null || array.length <= 0) { return returnString; } for (int index = 0; index < array.length; index++) { String s = array[index]; if (s == null) { s = ""; } if (index != array.length - 1) returnString += s + regex; else returnString += s; } return returnString; } /** * 根据传入字符串获得日期 * * @param dateStr * @param format * @return */ public static Date getDate(String dateStr, String format) { SimpleDateFormat sf = new SimpleDateFormat(format); Date date = null; try { date = sf.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } return date; } /** * 获得日期相减总月数 * * @param after * @param before * @param format * @return */ public static int getMinusMonth(Date after, String before, String format) { SimpleDateFormat sf = new SimpleDateFormat(format); try { return getMinusMonth(after, sf.parse(before)); } catch (ParseException e) { e.printStackTrace(); } return 0; } /** * 获得日期相减总月数 * * @param after * @param before * @param format * @return */ public static int getMinusMonth(String after, String before, String format) { SimpleDateFormat sf = new SimpleDateFormat(format); try { return getMinusMonth(sf.parse(after), sf.parse(before)); } catch (ParseException e) { e.printStackTrace(); } return 0; } /** * 获得日期相减总月数 * * @param after * @param before * @return */ public static int getMinusMonth(Date after, Date before) { Calendar calAfter = Calendar.getInstance(); calAfter.setTime(after); Calendar calBefore = Calendar.getInstance(); calBefore.setTime(before); int minus = (calAfter.get(Calendar.YEAR) - calBefore.get(Calendar.YEAR)) * 12 + (calAfter.get(Calendar.MONTH) - calBefore.get(Calendar.MONTH)); return minus; } /** * 当前时间 + 多少个月 * * @param date * @param AddMonth * @return */ public static Date dateAddMonth(Date date, int AddMonth) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.MONTH, AddMonth); return c.getTime(); } /** * 全角空格为12288,半角空格为32 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 * * 将字符串中的全角字符转为半角 * * @param src * 要转换的包含全角的任意字符串 * @return 转换之后的字符串 */ public static String toSemiangle(String src) { char[] c = src.toCharArray(); for (int index = 0; index < c.length; index++) { if (c[index] == 12288) {// 全角空格 c[index] = (char) 32; } else if (c[index] > 65280 && c[index] < 65375) {// 其他全角字符 c[index] = (char) (c[index] - 65248); } } return String.valueOf(c); } /*** * 获取时间间隔天数 * * @param beginDate * :开始时间 * @param endDate * :结束时间 * @return * @throws ParseException */ public static int getDaysBetween(String beginDate, String endDate) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date bDate = format.parse(beginDate); Date eDate = null; if (endDate != null) { eDate = format.parse(endDate); } else { String currentDay = format.format(new Date()); eDate = format.parse(currentDay); } Calendar d1 = new GregorianCalendar(); d1.setTime(bDate); Calendar d2 = new GregorianCalendar(); d2.setTime(eDate); int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR); int y2 = d2.get(Calendar.YEAR); if (d1.get(Calendar.YEAR) != y2) { d1 = (Calendar) d1.clone(); do { days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);// 得到当年的实际天数 d1.add(Calendar.YEAR, 1); } while (d1.get(Calendar.YEAR) != y2); } return days; } /*** * 获取几天前 * * @param datediff * :相隔的天数 * @param format * :返回的时间格式,默认为yyyy-MM-dd * @return */ public static String getDateBefore(int datediff, String format) { if (StrUtils.isNull(format)) { format = "yyyy-MM-dd"; } Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, -datediff); Date day = c.getTime(); SimpleDateFormat sdf = new SimpleDateFormat(format); String date = sdf.format(day); return date; } /*** * 获取指定日期的几天前的日期 * * @param datediff * :相隔的天数 * @param endTime * :指定日期 * @param format * :返回的时间格式,默认为yyyy-MM-dd * @return */ public static String getDateBefore(int datediff, String endTime, String format) { if (StrUtils.isNull(format)) { format = "yyyy-MM-dd"; } Calendar c = Calendar.getInstance(); if (!StrUtils.isNull(endTime)) { c.setTime(getDate(endTime, format)); } c.add(Calendar.DATE, -datediff); Date day = c.getTime(); SimpleDateFormat sdf = new SimpleDateFormat(format); String date = sdf.format(day); return date; } /*** * 获取连个日期时间的月份 * * @param beginTime * :起始时间 * @param endTime * :结束时间 * @param format * :返回的时间格式 默认为yyyy-mm * @return */ public static List<String> getMonthBetween(String beginTime, String endTime, String format) { ArrayList<String> result = null; try { result = new ArrayList<String>(); if (StrUtils.isNull(format)) { format = "yyyy-MM"; } SimpleDateFormat sdf = new SimpleDateFormat(format);// 格式化为年月 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(beginTime)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(sdf.parse(endTime)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); Calendar curr = min; while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } } catch (Exception e) { e.printStackTrace(); } return result; } /*** * 获取连个日期时间的年份 * * @param beginTime * :起始时间 * @param endTime * :结束时间 * @param format * :返回的时间格式 默认为yyyy * @return */ public static List<String> getYearBetween(String beginTime, String endTime, String format) { ArrayList<String> result = null; try { result = new ArrayList<String>(); if (StrUtils.isNull(format)) { format = "yyyy"; } SimpleDateFormat sdf = new SimpleDateFormat(format);// 格式化为年月 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(beginTime)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(sdf.parse(endTime)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); Calendar curr = min; while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.YEAR, 1); } } catch (Exception e) { e.printStackTrace(); } return result; } /** * 文件类型判断 * * @param fileName * @return */ public static boolean checkFileType(String fileName, String[] allowFiles) { for (String ext : allowFiles) { if (fileName.toLowerCase().endsWith(ext)) { return true; } } return false; } /** * 是不是手机号码 * * @param input * : 需要验证的字符串 * @return 是 true; 否 false */ public static boolean isMobile(String input) { if (null != input) { return Pattern.matches(mobileRegExp, input); } else { return false; } } /** * 创建文件夹 不存在创建,存在则忽略 * * @param path */ public static void mkdirs(String path) { File file = new File(path); if (!file.exists()) { file.mkdirs(); } } /*** * 判断指定的日期是否在当前时间之前 * @param time * @return */ public static boolean isBeforeToday (long time) { long current = new Date().getTime(); if ((current - time) > 0) { return true; } return false; } /*** * 获取当前年份 * @return */ public static int getCurrentYear () { Calendar cal = Calendar.getInstance(); return cal.get(Calendar.YEAR); } /*** * 获取当前月份 * @return */ public static int getCurrentMonth () { Calendar cal = Calendar.getInstance(); return cal.get(Calendar.MONTH) + 1; } /** * 递归删除空文件 * @param path */ public static void delEmptyPath(String path) { File file = new File(path); if (file.exists() && file.isDirectory()) { File[] files = file.listFiles(); if (files != null && files.length > 0) return; if (file.delete()) { delEmptyPath(file.getParent()); } } } }
标签:
原文地址:http://blog.csdn.net/u012965203/article/details/51272641