package com.hx.util; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.FileNameMap; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDataFormatter; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONObject; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import org.apache.poi.ss.usermodel.CellType; import org.springframework.cglib.beans.BeanMap; public class SimpleTool { public static SimpleDateFormat myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static DecimalFormat fmt = new DecimalFormat("0.00"); public static Byte[] lock = new Byte[] {0}; /**对象转map*/ public static Map objectToMap(Object obj) { if(obj == null) return null; return new org.apache.commons.beanutils.BeanMap(obj); } /** * 将对象装换为map * * @param bean * @return */ public static Map beanToMap(T bean) { Map map = new HashMap<>(); if (bean != null) { BeanMap beanMap = BeanMap.create(bean); for (Object key : beanMap.keySet()) { map.put(key + "", beanMap.get(key)); } } return map; } /** * 将对象装换为map * * @param bean * @return */ public static Map beanToMapS(Object bean) { Map map = new HashMap<>(); if (bean != null) { BeanMap beanMap = BeanMap.create(bean); for (Object key : beanMap.keySet()) { if(beanMap.get(key) != null){ map.put(key + "", beanMap.get(key).toString()); }else{ map.put(key + "", ""); } } } return map; } /** * 后台格式构建返回值格式列表-后台获取列表 * @param count 返回总条数 * @return JSONObject 特定格式的JSONObject */ public static JSONObject resAdminLsit(Integer status,String errMsg,JSONArray arr,Integer count){ JSONObject fObj = new JSONObject(); try{ fObj.put("code", status); fObj.put("count", count); fObj.put("msg", errMsg); fObj.put("data", arr); }catch (Exception e) { e.printStackTrace(); } return fObj; } /** * 获取指定格式的Double 类型数据 * * @param type * 转换格式的类型 默认为 "#.#" * @param e * 要转换的数据源 **/ public static Double getTypeDouble(String type, Double e) { if (!checkNotNull(type)) type = "0.00"; fmt = new DecimalFormat(type); fmt.setRoundingMode(RoundingMode.HALF_UP); // 保留小数点后两位并四舍五入,确保价钱准确 Double d = Double.valueOf(fmt.format(e)); return d; } /** * 首字母大写 * * @param str */ public static String capitalized(String str) { if ("".equals(str.trim()) || str == null) { return ""; } String key = str.substring(0, 1).toUpperCase(); String keys = key + str.substring(1, str.length()); return keys; } /** 判断参数是否为null,如果null抛出对应异常 */ public static void checkErrMsg(Object obj, String errMsg) { if (!checkNotNull(obj)) throw new RuntimeException(errMsg); } /*** 创建文件(自动生成文件夹。)(需要真实路径) **/ public static File createFile(String mkdirPath, String fileName) throws IOException { System.out.println(mkdirPath + fileName); // mkdirPath = // "E:\\work\\soft\\MyEclipse\\apache-tomcat-7.0.61\\webapps\\ROOT\\"; File f = new File(mkdirPath); if (!f.exists()) { f.mkdirs(); } File file = new File(f, fileName); if (!file.exists()) { file.createNewFile(); } // System.out.println(file.getAbsolutePath()); return file; } /** * 构建返回值格式 * * @param status * 返回状态 * @param errMsg * 返回附带信息 * @param inf * 返回实体值 * @return JSONObject 特定格式的JSONObject */ public static JSONObject res(Integer status, String errMsg, JSONObject inf) { JSONObject res = new JSONObject(); JSONObject fObj = new JSONObject(); try { res.put("status", status); res.put("errMsg", errMsg); fObj.put("res", res); fObj.put("inf", inf); } catch (Exception e) { e.printStackTrace(); } return fObj; } /** * Date类型转换为10位时间戳 * * @param time * @return */ public static Integer DateToTimestamp(Date time) { Timestamp ts = new Timestamp(time.getTime()); return (int) ((ts.getTime()) / 1000); } /** 判断当前时间是什么时候 **/ public static Boolean IsTime(Date date, Integer year, Integer month, Integer day, Integer hour, Integer minute) { Calendar cal = new GregorianCalendar(); cal.setTime(date); if (year != null) { int iyear = cal.get(Calendar.YEAR); if (iyear != year) return false; } if (month != null) { int imonth = cal.get(Calendar.MONTH);// 获取月份(月份从0开始计算的) imonth = imonth + 1; if (imonth != month) return false; } if (day != null) { int iday = cal.get(Calendar.DATE);// 获取日 if (iday != day) return false; } if (hour != null) { int ihour = cal.get(Calendar.HOUR_OF_DAY);// 24小时 0- 23 if (ihour != hour) return false; } if (minute != null) { int iminute = cal.get(Calendar.MINUTE); if (iminute != minute) return false; } // Boolean b = yearTag && monthTag && dayTag && hourTag && minuteTag; return true; } /** * 根据具体时间属性判断是否相同 * */ public static Boolean DateEquals(Date date1, Date date2, Boolean year, Boolean month, Boolean day, Boolean hour, Boolean minute) { Calendar calendar1 = new GregorianCalendar(); Calendar calendar2 = new GregorianCalendar(); calendar1.setTime(date1); calendar2.setTime(date2); if (year) { if (calendar1.get(Calendar.YEAR) != calendar2.get(Calendar.YEAR)) { return false; } } if (month) { if (calendar1.get(Calendar.MONTH) != calendar2.get(Calendar.MONTH)) { return false; } } if (day) { if (calendar1.get(Calendar.DATE) != calendar2.get(Calendar.DATE)) { return false; } } if (year) { if (calendar1.get(Calendar.HOUR_OF_DAY) != calendar2.get(Calendar.HOUR_OF_DAY)) { return false; } } if (year) { if (calendar1.get(Calendar.MINUTE) != calendar2.get(Calendar.MINUTE)) { return false; } } // Boolean b = yearTag && monthTag && dayTag && hourTag && minuteTag; return true; } /** 获取10位数时间戳 */ public static Integer getTenTime(Date date) { Timestamp ts = new Timestamp(date.getTime()); return (int) ((ts.getTime()) / 1000); } /** * 获取指定日期的明天 difDay 把日期往后增加一天.整数往后推,负数往前移动 * * @return date */ @SuppressWarnings("static-access") public static Date getDetailDay(Date today, int difDay) { Calendar calendar = new GregorianCalendar(); calendar.setTime(today); calendar.add(calendar.DATE, difDay);// 把日期往后增加一天.整数往后推,负数往前移动 Date d = calendar.getTime(); return d; } /** * 获取想要的格式的时间 * * @return String */ public static String getTypeDate(String type, Date date) { if (date == null) return null; if (SimpleTool.checkNotNull(type)) { myformat = new SimpleDateFormat(type); String returnDate = myformat.format(date); myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return returnDate; } else { String returnDate = myformat.format(date); return returnDate; } } /** * 比较两个时间天数差 startTime - endTime * * @param type * (无效) * @return String * @throws ParseException */ public static int getDiffDate(String type, Date startTime, Date endTime) throws ParseException { type = "yyyyMMdd"; SimpleDateFormat myformat = new SimpleDateFormat(type); int i = 0; i = (int) ((myformat.parse(myformat.format(startTime)).getTime() - myformat.parse(myformat.format(endTime)).getTime()) / (1000 * 60 * 60 * 24)); // return // myformat.parse(myformat.format(date1)).compareTo(myformat.parse(myformat.format(date2))); return i; } /** * 得到两个时间的分钟差 date1 - date2 这个是个奇葩。但是整型了。 * * @return int * @throws ParseException */ public static int getLeftDateForMinue(Date date1, Date date2) throws ParseException { long times = date1.getTime() - date2.getTime(); times = times / (1000 * 60); return (int) times; } /**把字符串转为特定时间格式 * * @param type 时间格式 * @param sDate 字符串时间(可以为空) * @return date * @throws ParseException */ public static Date parseStringForDate(String type, String sDate){ Date date = null; try { if(SimpleTool.checkNotNull(sDate)) { SimpleDateFormat myformat = new SimpleDateFormat(type); date = myformat.parse(sDate); } } catch (Exception e) { e.printStackTrace(); } return date; } /** * 判断是否为空 */ public static boolean checkNotNull(Object o) { boolean b = false; if (o != null && !"".equals(o)&&!"undefined".equals(o)&&!" ".equals(o)) { b = true; } return b; } /** * 判断是否为空 (多个) */ public static boolean checkNotNullM(Object[] os) { boolean b = true; for (Object o : os) { if (o == null || "".equals(o)) return false; } return b; } /** * 获取服务器端的webapps路径 * * @return */ public String findServerPath() { String classPath = this.getClass().getClassLoader().getResource("/").getPath(); try { classPath = URLDecoder.decode(classPath, "gb2312"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String[] strPath = classPath.split("/"); String path = ""; for (int i = 0; i < strPath.length; i++) { if (i > 0 && i <= 3) { path = path + strPath[i] + "/"; } } return path; } /** * 删除文件 输入真是路径 */ public static void deleteFile(String sPath) { File file = new File(sPath); // 判断目录或文件是否存在 if (file.exists()) { // 判断是否为文件 if (file.isFile()) { // 为文件时调用删除文件方法 deleteFileForOne(sPath); } else { // 为目录时调用删除目录方法 throw new RuntimeException("dir is no del"); // deleteDirectory(sPath); } } } /** * 删除目录(文件夹)以及目录下的文件 * * @param sPath * 被删除目录的文件路径 * @return 目录删除成功返回true,否则返回false */ public static boolean deleteDirectory(String sPath) { // 如果sPath不以文件分隔符结尾,自动添加文件分隔符 if (!sPath.endsWith(File.separator)) { sPath = sPath + File.separator; } File dirFile = new File(sPath); // 如果dir对应的文件不存在,或者不是一个目录,则退出 if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } Boolean flag = true; // 删除文件夹下的所有文件(包括子目录) File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { // 删除子文件 if (files[i].isFile()) { flag = deleteFileForOne(files[i].getAbsolutePath()); if (!flag) break; } // 删除子目录 else { flag = deleteDirectory(files[i].getAbsolutePath()); if (!flag) break; } } if (!flag) return false; // 删除当前目录 if (dirFile.delete()) { return true; } else { return false; } } /** * 删除单个文件 * * @param sPath * 被删除文件的文件名 * @return 单个文件删除成功返回true,否则返回false */ public static boolean deleteFileForOne(String sPath) { Boolean flag = false; File file = new File(sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } /** * 获取uuid */ public static String getUUIDName() { return UUID.randomUUID().toString(); } /** 获取异常信息 **/ public static String getExceptionMsg(Exception e) { StringBuffer emsg = new StringBuffer(); if (e != null) { StackTraceElement[] st = e.getStackTrace(); for (StackTraceElement stackTraceElement : st) { String exclass = stackTraceElement.getClassName(); String method = stackTraceElement.getMethodName(); emsg.append("[类:" + exclass + "]调用---" + method + "----时在第" + stackTraceElement.getLineNumber() + "行代码处发生异常!异常类型:" + e.toString() + "(" + e.getMessage() + ")\r\n"); } } return emsg.toString(); } /** * 获取指定格式的Double 类型数据 * * 转换格式的类型 默认为 "#.##" * @param e * 要转换的数据源 **/ public static Double getTypeDouble(Double e) { fmt.setRoundingMode(RoundingMode.HALF_UP); // 保留小数点后两位并四舍五入,确保价钱准确 Double d = Double.valueOf(fmt.format(e)); return d; } /** * SHA1 加密 * * @param decript * @return */ public static String SHA1(String decript) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(decript.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } public static String getLocalIP() { InetAddress addr = null; try { addr = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } byte[] ipAddr = addr.getAddress(); String ipAddrStr = ""; for (int i = 0; i < ipAddr.length; i++) { if (i > 0) { ipAddrStr += "."; } ipAddrStr += ipAddr[i] & 0xFF; } // System.out.println("i am ip:......"+ipAddrStr); return ipAddrStr; } /**随机生成字符串(0-9) * * @param lengthCount 长度 * @return */ public static String generateCardNo(Integer lengthCount) { if(!SimpleTool.checkNotNull(lengthCount)) { lengthCount = 6; } java.util.Random r=new java.util.Random(); StringBuilder str = new StringBuilder();//定义变长字符串 for(int i=0;i0) { byte[] datas2 = new byte[] {datas[0]}; hanzi = new String(datas2); }else { hanzi = ""; }*/ } return hanzi; } /***将汉字转成拼音(取首字母或全拼) * @param hanzi * @param full 是否全拼 * @return */ public static String convertHanzi2Pinyin(String hanzi,boolean full){ //获取第一个字 /* if(checkNotNull(hanzi)){ boolean isHave = true; Integer l = hanzi.length(); Integer index = 0; while (isHave) { String hanzi2 = hanzi.substring(index,index+1); if(isChineseChar(hanzi2)){ isHave = false; hanzi = hanzi2; }else{ if(index readExcelByeFile2(File excel_name) throws Exception { // 结果集 List list = new ArrayList(); HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(excel_name)); // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数 HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0); // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) { HSSFRow hssfrow = hssfsheet.getRow(j); if(hssfrow!=null){ int col = hssfrow.getPhysicalNumberOfCells(); // 单行数据 String[] arrayString = new String[col]; for (int i = 0; i < col; i++) { HSSFCell cell = hssfrow.getCell(i); if (cell == null) { arrayString[i] = ""; } else if (cell.getCellType() == CellType.NUMERIC) { // arrayString[i] = new Double(cell.getNumericCellValue()).toString(); short format = cell.getCellStyle().getDataFormat(); SimpleDateFormat sdf = null; if(format == 14 || format == 31 || format == 57 || format == 58){ //日期 sdf = new SimpleDateFormat("yyyy-MM-dd"); }else if (format == 20 || format == 32) { //时间 sdf = new SimpleDateFormat("HH:mm"); }else if (CellType.NUMERIC == cell.getCellType()) { if (HSSFDateUtil.isCellDateFormatted(cell)) { Date d = cell.getDateCellValue(); DateFormat formater = new SimpleDateFormat("yyyy年"); // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); arrayString[i] = formater.format(d); } else { arrayString[i] = new BigDecimal(cell.getNumericCellValue()).toString(); } } } else {// 如果EXCEL表格中的数据类型为字符串型 arrayString[i] = cell.getStringCellValue().trim(); } } list.add(arrayString); } } return list; } /** * 读取 Excel文件内容 * * @param excel_name * @param header 是否包括表头 * @return * @throws Exception */ public static List readExcelByeFileData(File excel_name,boolean header) throws Exception { // 结果集 List list = new ArrayList(); HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream( excel_name)); // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数 for(int s=0;s readExcelByeFile(File excel_name) throws Exception { // 结果集 List list = new ArrayList(); HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream( excel_name)); // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数 for(int s=0;s * @param request * @return * @author chenjiahe * @Date 2018年3月2日下午4:41:47 * @since JDK 1.7 */ public static String getClientIpAddress(HttpServletRequest request) { for (String header : HEADERS_TO_TRY) { String ip = request.getHeader(header); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { return ip; } } return request.getRemoteAddr(); } }