1.UUID工具类
import java.util.UUID; /** * UUID工具类 * @author wbw * */ public class UUIDUtil { public static String uuid(){ return UUID.randomUUID().toString().replaceAll("-", ""); } }2.Date工具类:时间的格式化
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.springframework.util.StringUtils; public class DateUtil { public static final String yyyy_MM_dd="yyyy-MM-dd"; public static final String yyyy_MM_dd_ZN="yyyy 年 MM 月 dd 日"; public static final String yyyy_MM_dd_ZN1="yyyy年MM月dd日"; public static final String yyyy_MM_dd_ZN2="yyyy年M月d日"; public static final String yyyy_MM_dd_HH="yyyy 年 MM 月 dd 日 HH 时"; public static final String yyyy_MM_dd_HH_mm="yyyy 年 MM 月 dd 日 HH 时mm分"; public static final String yyyy_MM_dd_HH_mm_ss="yyyy-MM-dd HH:mm:ss"; public static final String HH_mm_ss="HH:mm:ss"; public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public static String dateToStr(String pattern){ SimpleDateFormat sdf = new SimpleDateFormat(pattern); String str = sdf.format(new Date()); return str; } public static String dateToStr(){ return dateToStr(yyyy_MM_dd_HH_mm_ss); } public static String dateToStr(Date date){ return dateToStr(date, yyyy_MM_dd); } public static String dateToStr(Date date,String pattern){ if(date == null){ return ""; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); String str = sdf.format(date); return str; } /** * 时间String转Date * @param date * @param pattern * @return * @throws ParseException * @throws Exception */ public static Date strToDate(String date,String pattern) throws ParseException{ DateFormat format = new SimpleDateFormat(pattern); return format.parse(date); } /** * 时间String转Date * 默认 转化类型 yyyy-MM-dd * @param date * @return * @throws Exception */ public static Date strToDate(String date)throws Exception{ return strToDate(date, yyyy_MM_dd); } /** * 得到当前时间 * @return yyyy-MM-dd HH:mm:ss * @throws Exception */ public static Date getCurrDate() throws Exception{ String dateStr = dateToStr(yyyy_MM_dd_HH_mm_ss); SimpleDateFormat sdf = new SimpleDateFormat(yyyy_MM_dd_HH_mm_ss); return sdf.parse(dateStr); } public static int getLastDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); return cal.getActualMaximum(Calendar.DATE); } public static int getFirstDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); return cal.getMinimum(Calendar.DATE); } /** * 比较两个日期 * @param start * @param end * @return * start > end 则返回 1 * start = end 则返回 0 * start < end 则返回 -1 */ public static int dateCompare(Date start, Date end) throws Exception{ if(start == null && end == null){ return 0; } if(start == null && end != null){ return -1; } if(start != null && end == null){ return 1; } Calendar cal= Calendar.getInstance(); cal.setTime(start); Calendar ca2 = Calendar.getInstance(); ca2.setTime(end); return cal.compareTo(ca2); } /** * 判断一个时间是否在一段时间内 * @param start * @param date 比较的日期 * @param end * @return * start <= date <= end 则返回 true * 其他则返回false */ public static boolean dateInTwoDays(Date start, Date date, Date end) throws Exception{ if(start == null || end == null || date == null){ return false; } Calendar ca1= Calendar.getInstance(); ca1.setTime(start); Calendar ca2 = Calendar.getInstance(); ca2.setTime(end); Calendar ca3= Calendar.getInstance(); ca3.setTime(date); if( ca2.compareTo(ca1) > -1 && ca3.compareTo(ca1) > -1 && ca2.compareTo(ca3) > -1){ return true; } return false; } /** * 得到当前月的最后一天 * @return yyyy-MM-dd HH:mm:ss */ public static String getLastDayOfMonth() { Calendar cal = Calendar.getInstance(); String yearMonth = cal.get(Calendar.YEAR)+ "-"; if((cal.get(Calendar.MONTH)+1) < 10){ yearMonth += "0"+(cal.get(Calendar.MONTH)+1); }else{ yearMonth += (cal.get(Calendar.MONTH)+1); } return yearMonth + "-" + cal.getActualMaximum(Calendar.DATE) + " 23:59:59"; } /** * 得到当前月的第一天 * @return yyyy-MM-dd HH:mm:ss */ public static String getFirstDayOfMonth() { Calendar cal = Calendar.getInstance(); String yearMonth = cal.get(Calendar.YEAR)+ "-"; if((cal.get(Calendar.MONTH)+1) < 10){ yearMonth += "0"+(cal.get(Calendar.MONTH)+1); }else{ yearMonth += (cal.get(Calendar.MONTH)+1); } return yearMonth + "-01 00:00:00"; } /** * 得到当前年 * @return yyyy */ public static String getNowYear() { Calendar cal = Calendar.getInstance(); return cal.get(Calendar.YEAR) + ""; } public static int getYearByDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.YEAR); } /** * 得到当前月 * @return mm */ public static String getNowMonth() { Calendar cal = Calendar.getInstance(); return cal.get(Calendar.MONTH) + ""; } public static int getMonthByDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.MONTH); } /** * 得到当前日 * @return mm */ public static String getNowDay() { Calendar cal = Calendar.getInstance(); return cal.get(Calendar.DATE) + ""; } public static int getDayByDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.DATE); } /** * 根据年月日得到日期 * @return mm */ public static Date getDate(int year,int month, int date) { Calendar cal = Calendar.getInstance(); cal.set(year, month, date); return cal.getTime(); } /** * 计算两个日期将的天数 * @param startDate * @param endDate * @return 天数 */ public static int daysBetween(Date startDate, Date endDate) { try { if(startDate == null || endDate == null){ return 0; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); startDate = sdf.parse(sdf.format(startDate)); endDate = sdf.parse(sdf.format(endDate)); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); long time1 = cal.getTimeInMillis (); cal.setTime(endDate); long time2 = cal.getTimeInMillis (); long between_days=(time2-time1)/ (1000*3600*24); return Integer.parseInt(String.valueOf (between_days)); } catch (Exception e) { e.printStackTrace(); } return 0; } /** * 计算年龄 * @param csrq 出生日期 * @return */ public static int calculationAge(Date csrq) { try { if(csrq == null ){ return 0; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String csyear = sdf.format(csrq).substring(0, 4); String nowYear = getNowYear(); return Integer.valueOf(nowYear) - Integer.valueOf(csyear); } catch (Exception e) { e.printStackTrace(); } return 0; } /** * 验证开始时间是否小于结束时间 * @param startDate * 开始时间 * @param endDate * 结束时间 * @throws Exception */ public static void checkTime(Date startDate, Date endDate) throws Exception { if(startDate==null){ throw new RuntimeException("开始时间不能为空"); } if(endDate==null){ throw new RuntimeException("结束时间不能为空"); } if(startDate.after(endDate)){ throw new RuntimeException("开始时间不能大于结束时间"); } } }3.Session工具类:设置当前用户于session中或获取session中的用户
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; public class SpringWebUtil { /** * 全局删除id标示 */ public static String GLOB_DELETE_ID_VAL = "globDeleteIdVal"; public static HttpServletRequest getRequest(){ ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); return requestAttributes==null? null : requestAttributes.getRequest(); } public static HttpSession getSession(){ return getRequest().getSession(false); } public static String getRealRootPath(){ return getRequest().getServletContext().getRealPath("/"); } public static String getIp() { ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); if(servletRequestAttributes!=null){ HttpServletRequest request = servletRequestAttributes.getRequest(); return request.getRemoteAddr(); } return null; } public static Object getSessionAttribute(String name){ HttpServletRequest request = getRequest(); return request == null?null:request.getSession().getAttribute(name); } public static void setSessionAttribute(String name,Object value){ HttpServletRequest request = getRequest(); if(request!=null){ request.getSession().setAttribute(name, value); } } public static Object getRequestAttribute(String name){ HttpServletRequest request = getRequest(); return request == null?null:request.getAttribute(name); } public static void setRequestAttribute(String name,Object value){ HttpServletRequest request = getRequest(); if(request!=null){ request.setAttribute(name, value); } } public static String getContextPath() { return getRequest().getContextPath(); } public static void removeSessionAttribute(String name) { getRequest().getSession().removeAttribute(name); } }
4.Bean工具类:
import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import org.springframework.beans.BeansException; import org.springframework.beans.FatalBeanException; import org.springframework.util.Assert; public class BeanUtils extends org.springframework.beans.BeanUtils { public static void copyNotNullProperties(Object source, Object target){ copyNotNullProperties(source, target,null,null); } public static void copyNotNullProperties(Object source, Object target, String...ignoreProperties) throws BeansException { copyNotNullProperties(source, target, null, ignoreProperties); } public static void copyNotNullProperties(Object source, Object target, Class<?> editable, String[] ignoreProperties){ Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); } actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null; for (PropertyDescriptor targetPd : targetPds) { if (targetPd.getWriteMethod() != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null && sourcePd.getReadMethod() != null) { try { Method readMethod = sourcePd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if(value!=null){ Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException("Could not copy properties from source to target", ex); } } } } } }5.CglibBean工具类:
import java.util.Map; import org.springframework.cglib.beans.BeanGenerator; import org.springframework.cglib.beans.BeanMap; public class CglibBeanUtil { /** * 实体Object */ public Object object = null; /** * 属性map */ public BeanMap beanMap = null; public CglibBeanUtil() { } public CglibBeanUtil(Map<String,Class<?>> propertyMap) { this.object = generateBean(propertyMap); this.beanMap = BeanMap.create(this.object); } /** * 给bean属性赋值 * @param property 属性名 * @param value 值 */ public void setValue(String property, Object value) { beanMap.put(property, value); } /** * 通过属性名得到属性值 * @param property 属性名 * @return 值 */ public Object getValue(String property) { return beanMap.get(property); } /** * 得到该实体bean对象 * @return */ public Object getObject() { return this.object; } private Object generateBean(Map<String,Class<?>> propertyMap) { BeanGenerator generator = new BeanGenerator(); for (String key : propertyMap.keySet()) { generator.addProperty(key, propertyMap.get(key)); } return generator.create(); } }6.Exception工具类:将异常堆信息以字符串的格式返回
public class ExceptionUtil { /** * <p> * 将异常堆栈信息以字符串的格式返回 * </p> * * @param e 异常对象 * @return */ public static String createStackTrackMessage(Exception e) { StringBuffer messsage = new StringBuffer(); if (e != null) { messsage.append(e.getClass()).append(": ").append(e.getMessage()).append("\n"); StackTraceElement[] elements = e.getStackTrace(); for (StackTraceElement stackTraceElement : elements) { messsage.append("\t").append(stackTraceElement.toString()).append("\n"); } } return messsage.toString(); } }<strong> </strong>7.Cookie工具类
import javax.servlet.http.Cookie; import com.bjhy.platform.commons.consist.CommonConsist; public class CookieUtil { public static String getProperty(Cookie[] cookies, String name){ if(cookies == null) return null; for (Cookie cookie : cookies) { if(cookie.getName().equals(name)){ return cookie.getValue(); } } return null; } public static String getAppToken(Cookie[] cookies){ return getProperty(cookies, CommonConsist.TOKEN_COOKIE); } public static boolean containsPropery(Cookie[] cookies, String name){ if(cookies == null) return false; for (Cookie cookie : cookies) { if(cookie.getName().equals(name)){ return true; } } return false; } public static boolean containsAppToken(Cookie[] cookies){ return containsPropery(cookies, CommonConsist.TOKEN_COOKIE); } }8.hibernate 工具类,用于获取sessionFactory
package com.my.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; /** * hibernate4工具类 * @author wbw * */ @SuppressWarnings("deprecation") public class Hibernate4Util { private static final SessionFactory sessionFactory; /** * 初始化hibernate */ static { try { Configuration cfg = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).build(); sessionFactory = cfg.buildSessionFactory(serviceRegistry); } catch (Throwable e) { throw new ExceptionInInitializerError(e); } } private Hibernate4Util(){} /** * 获取开着的session * @return */ public static Session getSession(){ //*openSession必须关闭,currentSession在事务结束后自动关闭 // *openSession没有和当前线程绑定,currentSession和当前线程绑定 // return sessionFactory.openSession(); return sessionFactory.getCurrentSession(); } /** * 关闭sessionFactory */ public static void closeSession(){ sessionFactory.close(); } /** * 获取SessionFactory * @return */ public static SessionFactory getSessionFactory() { return sessionFactory; } }
package com.my.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * hibernate4工具类 * @author wbw * */ @SuppressWarnings("deprecation") public class Hibernate3Util { private static final SessionFactory sessionFactory; /** * 初始化hibernate */ static { try { //此方法已经过时 sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable e) { throw new ExceptionInInitializerError(e); } } private Hibernate3Util(){} /** * 获取开着的session * @return */ public static Session getSession(){ //*openSession必须关闭,currentSession在事务结束后自动关闭 // *openSession没有和当前线程绑定,currentSession和当前线程绑定 // return sessionFactory.openSession(); return sessionFactory.getCurrentSession(); } /** * 关闭sessionFactory */ public static void closeSession(){ sessionFactory.close(); } /** * 获取SessionFactory * @return */ public static SessionFactory getSessionFactory() { return sessionFactory; } }9.Logger工具类用于系统中打印输出日志信息:
/** * 日志对象 * @author wbw * */ public class LoggerUtils { /** * log对象 */ private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getRootLogger(); /** * 日志信息 * @param message 输出信息 */ final public static void info(Object message) { log.info(message); } /** * 调试信息 * @param message 输出信息 */ final public static void debug(Object message) { log.debug(message); } /** * 错误信息 * @param message 输出信息 */ final public static void error(Object message) { log.error(message); } /** * 警告信息 * @param message 输出信息 */ final public static void warn(Object message) { log.warn(message); } /** * 严重错误信息 * @param message 输出信息 */ final public static void fatal(Object message) { log.fatal(message); } }10.Arith计算工具类,由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精 确的浮点数运算,包括加减乘除和四舍五入。
import java.math.BigDecimal; /** */ public class Arith { // 默认除法运算精度 /** * DEF_DIV_SCALE */ private static final int DEF_DIV_SCALE = 10; // 这个类不能实例化 /** * scaleStr */ private static String scaleStr = "小数位数必须为大于等于0的正整数"; /** * 提供精确的加法运算。 * * @param v1 * 被加数 * @param v2 * 加数 * @return 两个参数的和 */ public static double add(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2).doubleValue(); } /** * 提供精确的减法运算。 * * @param v1 * 被减数 * @param v2 * 减数 * @return 两个参数的差 */ public static double sub(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2).doubleValue(); } /** * 提供精确的乘法运算。 * * @param v1 * 被乘数 * @param v2 * 乘数 * @return 两个参数的积 */ public static double mul(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2).doubleValue(); } /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。 * * @param v1 * 被除数 * @param v2 * 除数 * @return 两个参数的商 */ public static double div(double v1, double v2) { return div(v1, v2, DEF_DIV_SCALE); } /** * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。 * * @param v1 * 被除数 * @param v2 * 除数 * @param scale * 表示表示需要精确到小数点以后几位。 * @return 两个参数的商 */ public static double div(double v1, double v2, int scale) { if (scale < 0) { throw new IllegalArgumentException(scaleStr); } BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 提供精确的小数位四舍五入处理。 * * @param v * 需要四舍五入的数字 * @param scale * 小数点后保留几位 * @return 四舍五入后的结果 */ public static double round(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException(scaleStr); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 对eval对象进行精度和小数位数控制 * @param object object * @param scale scale * @return double */ public static double roundForEval(Object object, int scale) { if (scale < 0) { throw new IllegalArgumentException(scaleStr); } return round(Double.valueOf(object.toString()), scale); } /** * double类型转String 类型的小数点后的00 * @param num double参数 * @return String 类型 */ public static String doubleTransform(double num){ String strNum = num+""; int a = strNum.indexOf("."); if(a>0){ //获取小数点后面的数字 String dianAfter = strNum.substring(a+1); if("0".equals(dianAfter)){ return strNum+"0"; }else{ if(dianAfter.length()==1){ return strNum +"0"; }else{ return strNum; } } }else{ return strNum+".00"; } } };
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.StringReader; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.AndFileFilter; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.NotFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.log4j.Logger; public class FileUtil { private static Logger logger = Logger.getLogger(FileUtil.class); public static boolean string2File(String res, String filePath) { boolean flag = true; BufferedReader bufferedReader = null; BufferedWriter bufferedWriter = null; try { File distFile = new File(filePath); if (!distFile.getParentFile().exists()) { distFile.getParentFile().mkdirs(); } bufferedReader = new BufferedReader(new StringReader(res)); bufferedWriter = new BufferedWriter(new FileWriter(distFile)); char[] buf = new char[1024]; int len; while ((len = bufferedReader.read(buf)) != -1) { bufferedWriter.write(buf, 0, len); } bufferedWriter.flush(); bufferedReader.close(); bufferedWriter.close(); } catch (IOException e) { flag = false; logger.error("将字符串填充到文件失败", e); } return flag; } public static void copyFile(String resFilePath, String distFolder) throws IOException { File resFile = new File(resFilePath); File distFile = new File(distFolder); if (resFile.isDirectory()) { FileUtils.copyDirectoryToDirectory(resFile, distFile); } else if (resFile.isFile()) { FileUtils.copyFileToDirectory(resFile, distFile, true); } } public static void deleteFile(String targetPath) throws IOException { File targetFile = new File(targetPath); if (targetFile.isDirectory()) { FileUtils.deleteDirectory(targetFile); } else if (targetFile.isFile()) { targetFile.delete(); } } public static void moveFile(String resFilePath, String distFolder) throws IOException { File resFile = new File(resFilePath); File distFile = new File(distFolder); if (resFile.isDirectory()) { FileUtils.copyDirectory(resFile, distFile, true); } else if (resFile.isFile()) { FileUtils.copyDirectory(resFile, distFile, true); } } public static long genFileSize(String distFilePath) { File distFile = new File(distFilePath); if (distFile.isFile()) { return distFile.length(); } if (distFile.isDirectory()) { return FileUtils.sizeOfDirectory(distFile); } return -1L; } public static boolean isExist(String filePath) { return new File(filePath).exists(); } public static String[] listFilebySuffix(String folder, String suffix) { IOFileFilter fileFilter1 = new SuffixFileFilter(suffix); IOFileFilter fileFilter2 = new NotFileFilter( DirectoryFileFilter.INSTANCE); FilenameFilter filenameFilter = new AndFileFilter(fileFilter1, fileFilter2); return new File(folder).list(filenameFilter); } }12.StringUtils工具类
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public abstract class StringUtils extends org.apache.commons.lang.StringUtils{ private static final String FOLDER_SEPARATOR = "/"; private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; private static final String TOP_PATH = ".."; private static final String CURRENT_PATH = "."; private static final char EXTENSION_SEPARATOR = '.'; public static String[] addStringToArray(String[] array, String str) { if ((array == null) || (array.length < 0)) { return new String[] { str }; } String[] newArr = new String[array.length + 1]; System.arraycopy(array, 0, newArr, 0, array.length); newArr[array.length] = str; return newArr; } public static String applyRelativePath(String path, String relativePath) { int separatorIndex = path.lastIndexOf("/"); if (separatorIndex != -1) { String newPath = path.substring(0, separatorIndex); if (!relativePath.startsWith("/")) { newPath = newPath + "/"; } return newPath + relativePath; } return relativePath; } public static String arrayToCommaDelimitedString(Object[] arr) { return arrayToDelimitedString(arr, ","); } public static String arrayToDelimitedString(Object[] arr, String delim) { if (arr == null) { return ""; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < arr.length; i++) { if (i > 0) { sb.append(delim); } sb.append(arr[i]); } return sb.toString(); } public static String capitalize(String str) { return changeFirstCharacterCase(str, true); } private static String changeFirstCharacterCase(String str, boolean capitalize) { if ((str == null) || (str.length() == 0)) { return str; } StringBuffer buf = new StringBuffer(str.length()); if (capitalize) { buf.append(Character.toUpperCase(str.charAt(0))); } else { buf.append(Character.toLowerCase(str.charAt(0))); } buf.append(str.substring(1)); return buf.toString(); } public static String cleanPath(String path) { String pathToUse = replace(path, "\\", "/"); int prefixIndex = pathToUse.indexOf(":"); String prefix = ""; if (prefixIndex != -1) { prefix = pathToUse.substring(0, prefixIndex + 1); pathToUse = pathToUse.substring(prefixIndex + 1); } String[] pathArray = delimitedListToStringArray(pathToUse, "/"); List pathElements = new LinkedList(); int tops = 0; for (int i = pathArray.length - 1; i >= 0; i--) { if (!".".equals(pathArray[i])) { if ("..".equals(pathArray[i])) { tops++; } else if (tops > 0) { tops--; } else { pathElements.add(0, pathArray[i]); } } } for (int i = 0; i < tops; i++) { pathElements.add(0, ".."); } return prefix + collectionToDelimitedString(pathElements, "/"); } public static String collectionToCommaDelimitedString(Collection coll) { return collectionToDelimitedString(coll, ","); } public static String collectionToDelimitedString(Collection coll, String delim) { return collectionToDelimitedString(coll, delim, "", ""); } public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) { if (coll == null) { return ""; } StringBuffer sb = new StringBuffer(); Iterator it = coll.iterator(); int i = 0; while (it.hasNext()) { if (i > 0) { sb.append(delim); } sb.append(prefix).append(it.next()).append(suffix); i++; } return sb.toString(); } public static Set commaDelimitedListToSet(String str) { Set set = new TreeSet(); String[] tokens = commaDelimitedListToStringArray(str); for (String element : tokens) { set.add(element); } return set; } public static String[] commaDelimitedListToStringArray(String str) { return delimitedListToStringArray(str, ","); } public static int countOccurrencesOf(String str, String sub) { if ((str == null) || (sub == null) || (str.length() == 0) || (sub.length() == 0)) { return 0; } int count = 0; int pos = 0; int idx = 0; while ((idx = str.indexOf(sub, pos)) != -1) { count++; pos = idx + sub.length(); } return count; } public static String delete(String inString, String pattern) { return replace(inString, pattern, ""); } public static String deleteAny(String inString, String charsToDelete) { if ((inString == null) || (charsToDelete == null)) { return inString; } StringBuffer out = new StringBuffer(); for (int i = 0; i < inString.length(); i++) { char c = inString.charAt(i); if (charsToDelete.indexOf(c) == -1) { out.append(c); } } return out.toString(); } public static String[] delimitedListToStringArray(String str, String delimiter) { if (str == null) { return new String[0]; } if (delimiter == null) { return new String[] { str }; } List result = new ArrayList(); if ("".equals(delimiter)) { for (int i = 0; i < str.length(); i++) { result.add(str.substring(i, i + 1)); } } else { int pos = 0; int delPos = 0; while ((delPos = str.indexOf(delimiter, pos)) != -1) { result.add(str.substring(pos, delPos)); pos = delPos + delimiter.length(); } if ((str.length() > 0) && (pos <= str.length())) { result.add(str.substring(pos)); } } return toStringArray(result); } public static boolean endsWithIgnoreCase(String str, String suffix) { if ((str == null) || (suffix == null)) { return false; } if (str.endsWith(suffix)) { return true; } if (str.length() < suffix.length()) { return false; } String lcStr = str.substring(str.length() - suffix.length()) .toLowerCase(); String lcSuffix = suffix.toLowerCase(); return lcStr.equals(lcSuffix); } public static String getFilename(String path) { if (path == null) { return null; } int separatorIndex = path.lastIndexOf("/"); return separatorIndex != -1 ? path.substring(separatorIndex + 1) : path; } public static String getFilenameExtension(String path) { if (path == null) { return null; } int sepIndex = path.lastIndexOf('.'); return sepIndex != -1 ? path.substring(sepIndex + 1) : null; } public static boolean hasLength(String str) { return (str != null) && (str.length() > 0); } public static boolean hasText(String str) { int strLen; if ((str == null) || ((strLen = str.length()) == 0)) { return false; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } public static Locale parseLocaleString(String localeString) { String[] parts = tokenizeToStringArray(localeString, "_ ", false, false); String language = parts.length > 0 ? parts[0] : ""; String country = parts.length > 1 ? parts[1] : ""; String variant = parts.length > 2 ? parts[2] : ""; return language.length() > 0 ? new Locale(language, country, variant) : null; } public static boolean pathEquals(String path1, String path2) { return cleanPath(path1).equals(cleanPath(path2)); } public static String quote(String str) { return str != null ? "'" + str + "'" : null; } public static Object quoteIfString(Object obj) { return (obj instanceof String) ? quote((String) obj) : obj; } public static String[] removeDuplicateStrings(String[] array) { if ((array == null) || (array.length < 0)) { return array; } Set set = new TreeSet(); String[] arrayOfString = array; int j = array.length; for (int i = 0; i < j; i++) { String element = arrayOfString[i]; set.add(element); } return toStringArray(set); } public static String replace(String inString, String oldPattern, String newPattern) { if (inString == null) { return null; } if ((oldPattern == null) || (newPattern == null)) { return inString; } StringBuffer sbuf = new StringBuffer(); int pos = 0; int index = inString.indexOf(oldPattern); int patLen = oldPattern.length(); while (index >= 0) { sbuf.append(inString.substring(pos, index)); sbuf.append(newPattern); pos = index + patLen; index = inString.indexOf(oldPattern, pos); } sbuf.append(inString.substring(pos)); return sbuf.toString(); } public static String[] sortStringArray(String[] array) { if ((array == null) || (array.length < 0)) { return new String[0]; } Arrays.sort(array); return array; } public static String[] split(String toSplit, String delimiter) { if ((!hasLength(toSplit)) || (!hasLength(delimiter))) { return null; } int offset = toSplit.indexOf(delimiter); if (offset < 0) { return null; } String beforeDelimiter = toSplit.substring(0, offset); String afterDelimiter = toSplit.substring(offset + delimiter.length()); return new String[] { beforeDelimiter, afterDelimiter }; } public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) { return splitArrayElementsIntoProperties(array, delimiter, null); } public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter, String charsToDelete) { if ((array == null) || (array.length == 0)) { return null; } Properties result = new Properties(); String[] arrayOfString1 = array; int j = array.length; for (int i = 0; i < j; i++) { String element = arrayOfString1[i]; if (charsToDelete != null) { element = deleteAny(element, charsToDelete); } String[] splittedElement = split(element, delimiter); if (splittedElement != null) { result.setProperty(splittedElement[0].trim(), splittedElement[1].trim()); } } return result; } public static boolean startsWithIgnoreCase(String str, String prefix) { if ((str == null) || (prefix == null)) { return false; } if (str.startsWith(prefix)) { return true; } if (str.length() < prefix.length()) { return false; } String lcStr = str.substring(0, prefix.length()).toLowerCase(); String lcPrefix = prefix.toLowerCase(); return lcStr.equals(lcPrefix); } public static String stripFilenameExtension(String path) { if (path == null) { return null; } int sepIndex = path.lastIndexOf('.'); return sepIndex != -1 ? path.substring(0, sepIndex) : path; } public static String[] tokenizeToStringArray(String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return new String[0]; } StringTokenizer st = new StringTokenizer(str, delimiters); List tokens = new ArrayList(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if ((!ignoreEmptyTokens) || (token.length() > 0)) { tokens.add(token); } } return toStringArray(tokens); } public static String[] toStringArray(Collection collection) { if (collection == null) { return null; } return (String[]) collection.toArray(new String[collection.size()]); } public static String trimLeadingWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while ((buf.length() > 0) && (Character.isWhitespace(buf.charAt(0)))) { buf.deleteCharAt(0); } return buf.toString(); } public static String trimTrailingWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while ((buf.length() > 0) && (Character.isWhitespace(buf.charAt(buf.length() - 1)))) { buf.deleteCharAt(buf.length() - 1); } return buf.toString(); } public static String trimWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); do { buf.deleteCharAt(0); if (buf.length() <= 0) { break; } } while (Character.isWhitespace(buf.charAt(0))); while ((buf.length() > 0) && (Character.isWhitespace(buf.charAt(buf.length() - 1)))) { buf.deleteCharAt(buf.length() - 1); } return buf.toString(); } public static String uncapitalize(String str) { return changeFirstCharacterCase(str, false); } public static String unqualify(String qualifiedName) { return unqualify(qualifiedName, '.'); } public static String unqualify(String qualifiedName, char separator) { return qualifiedName .substring(qualifiedName.lastIndexOf(separator) + 1); } }13.Email工具类 用于发送邮件
import java.io.File; import java.util.Date; import java.util.Properties; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; /** * 邮件工具类 * * @author chenjun * */ public class EmailUtil { private JavaMailSender javaMailSender; private String username; public EmailUtil(String host, int port, String username, String password) { this.username = username; JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl(); javaMailSenderImpl.setHost(host); javaMailSenderImpl.setPort(port); javaMailSenderImpl.setUsername(username); javaMailSenderImpl.setPassword(password); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.auth", true); javaMailProperties.put("prop", true); javaMailProperties.put("mail.smtp.timeout", 25000); javaMailSenderImpl.setJavaMailProperties(javaMailProperties); javaMailSender = javaMailSenderImpl; } /** * 发送文本内容 * * @param to * 目标邮箱 * @param subject * 主题 * @param body * 内容 */ public void sendContent(String to, String subject, String body) { SimpleMailMessage simpleMessage = new SimpleMailMessage(); simpleMessage.setFrom(username);// 发送人名片 simpleMessage.setTo(to);// 收件人邮箱 simpleMessage.setSubject(subject);// 邮件主题 simpleMessage.setSentDate(new Date());// 邮件发送时间 simpleMessage.setText(body); javaMailSender.send(simpleMessage); } /** * 发送文本内容,带附件 * * @param to * 目标邮箱 * @param subject * 主题 * @param body * 内容 * @param file */ public void sendContent(String to, String subject, String body, File file) { sendContent(to, subject, body, new File[] { file }); } /** * 发送文本内容,带附件 * * @param to * 目标邮箱 * @param subject * 主题 * @param body * 内容 */ public void sendContent(String to, String subject, String body, File[] files) { if (files == null || files.length == 0) { sendContent(to, subject, body); } else { try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); helper.setFrom(username); helper.setTo(to); helper.setSubject(subject); helper.setText(body, true); helper.setSentDate(new Date()); for (int i = 0; i < files.length; i++) { helper.addAttachment( MimeUtility.encodeText(files[i].getName()), files[i]); } javaMailSender.send(mimeMessage); } catch (Exception e) { e.printStackTrace(); } } } }14.拼音操作工具类
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import org.apache.commons.lang.StringUtils; /** * @className:PinyingUtil.java * @classDescription:拼音操作工具类 */ public class PinYinUtil { private static final String DEFAULT_SEPARATOR = ""; private static final String SPACE_SEPARATOR = " "; static HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat(); static{ outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V); } public PinYinUtil() { } /** * 根据汉字返回全拼和简拼的集合,默认用空格分隔 * @param hanyu * @return * @throws Exception */ public static Set<String> hanyuToPyAndJp(String hanyu)throws Exception{ return hanyuToPyAndJp(hanyu, DEFAULT_SEPARATOR); } /** * 根据汉字返回全拼和简拼的集合,按指定分隔符分隔 * @param hanyu * @param separator * @return * @throws Exception */ public static Set<String> hanyuToPyAndJp(String hanyu, String separator) throws Exception { Set<String> resultSet = hanyuToPy(hanyu, separator); separator = " "; Set<String> resultSet2 = hanyuToPy(hanyu, " "); for (String pinyin : resultSet2) { String[] items = pinyin.split(separator); StringBuffer sb = new StringBuffer(); for (String item : items) { sb.append(item.substring(0, 1)); } resultSet.add(sb.toString()); } return resultSet; } /** * 根据汉字返回简拼的集合 * @param hanyu * @return * @throws Exception */ public static Set<String> hanyuToJp(String hanyu) throws Exception { String separator = " "; Set<String> resultSet = hanyuToPy(hanyu,separator); Set<String> jpSet = new HashSet<String>(); for (String pinyin : resultSet) { String[] items = pinyin.split(separator); StringBuffer sb = new StringBuffer(); for (String item : items) { sb.append(item.substring(0, 1)); } jpSet.add(sb.toString()); } return jpSet; } /** * 根据汉字返回简拼的集合字符串,默认空格关联比如 ab bd * @param hanyu * @return * @throws Exception */ public static String hanyuToJpStr(String hanyu) throws Exception { return hanyuToJpStr(hanyu, " "); } /** * 根据汉字返回简拼的集合字符串,按照指定关联符进行关联比如 ab,bd * @param hanyu * @param join * @return * @throws Exception */ public static String hanyuToJpStr(String hanyu,String join) throws Exception { String separator = " "; Set<String> resultSet = hanyuToPy(hanyu,separator); StringBuffer result = new StringBuffer(); Set<String> jpSet = new HashSet<String>(); for (String pinyin : resultSet) { String[] items = pinyin.split(separator); StringBuffer sb = new StringBuffer(); for (String item : items) { if(StringUtils.isNotEmpty(item)) sb.append(item.substring(0, 1)); } jpSet.add(sb.toString()); } for (String jp : jpSet) { result.append(jp).append(join); } return result.toString().trim(); } /** * 根据汉字返回拼音的集合 * @param hanyu * @return * @throws Exception */ public static Set<String> hanyuToPy(String hanyu) throws Exception { return hanyuToPy(hanyu, DEFAULT_SEPARATOR); } /** * 根据汉字返回拼音的集合字符串,默认空格关联比如 ab bd * @param hanyu * @return * @throws Exception */ public static String hanyuToPyStr(String hanyu) throws Exception{ return hanyuToPyStr(hanyu, DEFAULT_SEPARATOR, SPACE_SEPARATOR); } public static String hanyuToPyStr(String hanyu,String separator,String dySeparator) throws Exception{ Set<String> set = hanyuToPy(hanyu, separator); StringBuffer sb = new StringBuffer(); for (String dy : set) { sb.append(dy).append(dySeparator); } if(set.size()>0){ int index = sb.lastIndexOf(dySeparator); sb.replace(index, sb.length(), ""); } return sb.toString(); } public static Set<String> hanyuToPy(String hanyu, String separator) throws Exception { List<String[]> list = new ArrayList<String[]>(); Set<String> resultSet = new HashSet<String>(); if(StringUtils.isEmpty(hanyu))return resultSet; for (int i = 0; i < hanyu.length(); i++) { String[] pinyinArray = null; char chineseChar = hanyu.charAt(i); if (isHanzi(chineseChar)) { pinyinArray = PinyinHelper.toHanyuPinyinStringArray( chineseChar, outputFormat); } else { pinyinArray = new String[] { chineseChar + DEFAULT_SEPARATOR }; } if(pinyinArray!=null){ list.add(pinyinArray); } } buildItem(list, 0, DEFAULT_SEPARATOR, separator, resultSet); return resultSet; } protected static boolean isHanzi(char oneChar) { if ((oneChar >= '\u4e00' && oneChar <= '\u9fa5') || (oneChar >= '\uf900' && oneChar <= '\ufa2d')) { return true; } return false; } private static void buildItem(List<String[]> list, int index, String sb, String separator, Set<String> resultSet) { if (index == list.size()) { if (StringUtils.isNotEmpty(sb)) { if (StringUtils.isNotEmpty(separator)) { resultSet.add(sb.substring(1)); } else { resultSet.add(sb); } } return; } String[] items = list.get(index); for (String item : items) { buildItem(list, index + 1, sb + separator + item, separator, resultSet); } } }15.解压文件工具类
import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; /** * @Description 文件压缩解压 * @author wbw */ public class ZipFileUtil { /** * 解压文件 * @param zipFile * 解压文件对象 * @param descDir * 解压到的目录 * @throws Exception */ public static void unZipFile(File zipFile,String descDir)throws Exception{ int len = -1; File pathFile = new File(descDir); if(!pathFile.exists())pathFile.mkdirs(); ZipFile zip = new ZipFile(zipFile, "GBK"); for(Enumeration<ZipEntry> entries = zip.getEntries();entries.hasMoreElements();){ ZipEntry entry = (ZipEntry)entries.nextElement(); String zipEntryName = entry.getName(); InputStream in = zip.getInputStream(entry); String outPath = (descDir +"/"+ zipEntryName).replaceAll("\\*", "/"); //判断路径是否存在,不存在则创建文件路径 File file = new File(outPath.substring(0, outPath.lastIndexOf('/'))); if(!file.exists())file.mkdirs(); //判断文件全路径是否为文件夹,如果是上面已经创建,不需要解压 if(new File(outPath).isDirectory())continue; OutputStream out = new FileOutputStream(outPath); byte[] buf = new byte[1024]; while((len=in.read(buf))>0){ out.write(buf, 0, len); } in.close(); out.close(); } } }
/** * 字号转中文字符串 * @author wbw * 2014年11月20日 */ public class ZiAndHaoToChinaStr { private static final String LING ="零"; private static final String YI ="一"; private static final String ER ="二"; private static final String SAN ="三"; private static final String SI ="四"; private static final String WU ="五"; private static final String LIU ="六"; private static final String QI ="七"; private static final String BA ="八"; private static final String JIU ="九"; public static String toChinaStr(String str) { StringBuffer strb = new StringBuffer(); for(int i = 0 ; i < str.length();i++){ strb.append(toChinaChar(str.charAt(i))); } return strb.toString(); } private static String toChinaChar(Character ch){ String result= ""; switch(ch){ case '0': result = LING; break; case '1': result = YI; break; case '2': result = ER; break; case '3': result = SAN; break; case '4': result = SI; break; case '5': result = WU; break; case '6': result = LIU; break; case '7': result = QI; break; case '8': result = BA; break; case '9': result = JIU; break; default : result = ""; } return result; } }17.获取spring上下文的工具类
package cn.my.utils; import java.sql.Connection; import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * ClassPathXmlApplicationContext 类 */ public class ApplicationUtil { private ApplicationUtil() { } private static ApplicationContext context = null; private static final String fileName = "/applicationContext.xml"; /** * 初始化Spring环境 * @return * ApplicationContext */ public static ApplicationContext getInstance() { if (context == null) { context = new ClassPathXmlApplicationContext(fileName); } return context; } /** * 获得数据库连接 * @return * Connection */ public static Connection getConnection(){ if(context == null){ context = getInstance(); } DefaultSqlSessionFactory dssf = (DefaultSqlSessionFactory) context.getBean("sqlSessionFactory"); return dssf.openSession().getConnection(); } }