仅存放常用的工具类,自用

List item

  • 日期工具类
  • JSON工具类,在阿里的fastjson基础上封装
  • 随机数生成工具类
  • 字符串工具类
  • MultipartFile 转 File

    public class MultipartToFile {
        /**
         * MultipartFile 转 File
         * @param file
         * @throws Exception
         */
        public static File  multipartFileToFile(MultipartFile file ) throws Exception {
    
            File toFile = null;
            if(file.equals("")||file.getSize()<=0){
                file = null;
                return toFile;
            }else {
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            }
            return toFile;
        }
    
    
    
    
        public static void inputStreamToFile(InputStream ins, File file) {
            try {
                OutputStream os = new FileOutputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                ins.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        }
    

    上传文件至项目所在位置

    public class PhotoUtile {
    
    	// 照片保存路径
    		public static String filePath = System.getProperty("user.dir")+"/userPhoto/";
    
    
    		
    	public static StandardData PhotoUtile(MultipartFile file) throws IllegalStateException, IOException {
    		StandardData<String, Object> result = new StandardData<String, Object>();
    		TreeMap<String, Object> paramMap = new TreeMap<String, Object>();// 参数集
    		String fileOldName = file.getOriginalFilename();// 获取文件名
    		String suffixName = null;
    		String fileNewName = UUID.randomUUID().toString();// 生成新文件名
    		Long size = file.getSize();
    		if (fileOldName.lastIndexOf(".") > -1) {
    			suffixName = fileOldName.substring(fileOldName.lastIndexOf(".")).toLowerCase();// 获取文件后缀并转化为小写
    		} else {// 文件没有后缀,文件有错误
    			result.setError(FileMessageConstant._file_suffix_missed);
    			return result;
    		}
    		// 文件格式校验
    		Console.log(suffixName);
    		if (!(suffixName.equals(".jpeg") || suffixName.equals(".jpg") || suffixName.equals(".gif")
    				|| suffixName.equals(".bmp") || suffixName.equals(".png"))) {// 非图片
    			result.setError(FileMessageConstant._file_suffix_not_correct);
    			return result;
    		}
    		if (size > FileMessageConstant._pic_size_max) {// 文件过大
    			result.setError(FileMessageConstant._file_size_out_of_max + " 限制:" + FileMessageConstant._pic_size_max);
    			return result;
    		}
    		File dest = new File(filePath + fileNewName + suffixName);
    		System.out.println(System.getProperty("user.dir"));
    		System.out.println("dest     "+filePath + fileNewName + suffixName);
    		File targetFile = new File(filePath);
    		if (!targetFile.exists()) {
    			targetFile.mkdirs();
    		}
    		file.transferTo(dest);
    
    		String input = filePath + fileNewName + suffixName;
    		String output = filePath + fileNewName + "_min" + suffixName;
    		new ImgTools().ThumbnailsCompressPic(input, output, 100, (float) 1.0);
    		/*if(null != input && !"undefined".equals(input)) {
    			File readyRemove = new File(input);// 删除源文件
    			if (readyRemove.exists()) {
    				readyRemove.delete();
    			}
    		}*/
    		String photoUrl= fileNewName + /*"_min" +*/ suffixName;
    		String photoMiniUrl= fileNewName + "_min" + suffixName;
    		paramMap.put("photoUrl", photoUrl);
    		paramMap.put("photoMiniUrl", photoUrl);
    		result.setData(paramMap);
    		return result;
    	}
    
    	public static void delPhotoUtile(String oldPhotoUrl) throws IllegalStateException, IOException {
    		String delimeter = "/";
    		String[] temp=oldPhotoUrl.split(delimeter);
    		List<String> list = Arrays.asList(temp);
    		oldPhotoUrl=list.get((list.size()-1));
    
    		String delimeter2 = "\\.";
    		String[] temp2=oldPhotoUrl.split(delimeter2);
    		List<String> list2 = Arrays.asList(temp2);
    		String oldPhotoUrlMini=list2.get(0)+"_min."+list2.get(1);
    
    
    		File readyRemove = new File(filePath + oldPhotoUrl);// 删除源文件
    		if (readyRemove.exists()) {
    			readyRemove.delete();
    		}
    		File readyMiniRemove = new File(filePath + oldPhotoUrlMini);// 删除源文件
    		if (readyRemove.exists()) {
    			readyRemove.delete();
    		}
    
    	}
    }
    

    树型结构工具类

    /**
     * @ClassName TreeUtils
     * @Description 树型结构工具类
     * @Author Fang Yicheng
     * @Date 2020/2/28 17:53
     * @Version 1.0
     */
    public class TreeUtils {
    
        /**
         * 功能描述: 处理整棵树
         * @param allTree 整棵树
         * @param hasRoot 返回结果是否包含根节点
         * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
         * @Author: Fang Yicheng
         * @Date: 2020/3/2 13:45
         */
        public static List<Map<String, Object>> getTree(List<Map<String, Object>> allTree, boolean hasRoot) {
            return getTree(allTree, null, hasRoot, null, false);
        }
    
        /**
         * 功能描述: 树型结构数据处理。(不比对叶子节点,即用户拥有的,比如用户拥有的权限,权限是叶子节点。)
         * @param treeList 整颗树或者除叶子节点以外的树
         * @param leafList 叶子节点List 注:可以为空或null,为空或null时表示treeList为整颗树。
         * @param hasRoot 返回结果是否包含根节点: true:返回全部, false:返回除顶层根节点以外的数据(如 "1"节点这一层不返回,从 "1/3"节点开始返回)
         * @param leafArrayName 叶子节点返回数据结构中的数组名称(注:leafList不为空且需要改变叶子节点数组名称才使用)
         * @return: List<Map<String, Object>> 返回treeList
         * @Author: Fang Yicheng
         * @Date: 2020/2/28 17:46
         */
        public static List<Map<String, Object>> getTree(List<Map<String, Object>> treeList, List<Map<String, Object>> leafList, boolean hasRoot, String leafArrayName) {
            return getTree(treeList, leafList, hasRoot, leafArrayName, false);
        }
    
        /**
         * 功能描述: 树型结构数据处理。
         * @param treeList 整颗树或者除叶子节点以外的树
         * @param leafList 叶子节点List 注:可以为空或null,为空或null时表示treeList为整颗树。
         * @param hasRoot 返回结果是否包含根节点: true:返回全部, false:返回除顶层根节点以外的数据(如 "1"节点这一层不返回,从 "1/3"节点开始返回)
         * @param leafArrayName 叶子节点返回数据结构中的数组名称(leafList不为空且需要改变叶子节点数组名称才使用,)
         * @param compareLeafList 是否比对leafList: true:返回leafList中的节点以及父级节点。 false:不进行比对
         * @return: List<Map<String, Object>> 返回treeList
         * @Author: Fang Yicheng
         * @Date: 2020/2/28 17:46
         */
        public static List<Map<String, Object>> getTree(List<Map<String, Object>> treeList, List<Map<String, Object>> leafList, boolean hasRoot, String leafArrayName, boolean compareLeafList) {
            Map<String, Map<String, Object>> allNodeMap = new LinkedHashMap<>();
            // 将节点放入allNodeMap中
            treeList.forEach(node -> {
                if(CollectionUtil.isNotEmpty(leafList)) {
                    node.put("leaf", 0); // 将所有节点初始化为非叶子节点。
                }
                allNodeMap.put((String) node.get("path"), node);
            });
            if(StringUtils.isBlank(leafArrayName)) {
                leafArrayName = "children"; // 权限那边要单独使用"permissions"作为叶子节点数组的名字
            }
            if(!compareLeafList) { // 如果需要比对叶子节点,则不处理
                handleAllNode(allNodeMap);
            }
            if(CollectionUtil.isNotEmpty(leafList)) {
                // 遍历叶子节点
                for (Map<String, Object> leaf : leafList) {
                    String path = (String) leaf.get("path");
                    // 判断叶子节点的上层节点是否存在于现有节点中。
                    Map<String, Object> parentNodeMap = allNodeMap.get(path);
                    // 如果parentNodeMap不为空 则存在
                    if (parentNodeMap == null) {
                        continue;
                    }
                    // 在parentNodeMap中放入“leafArrayName”的值的key
                    if (!parentNodeMap.containsKey(leafArrayName)) {
                        parentNodeMap.put(leafArrayName, new ArrayList<>());
                    }
                    leaf.put("path", path + leaf.get("id") + "/");
                    leaf.put("leaf", 1); // 设置为叶子节点
                    ((List) parentNodeMap.get(leafArrayName)).add(leaf);
                    if(!compareLeafList) {
                        continue;
                    }
                    // 比对leafList,放入leafList中存在的节点以及父级节点
                    while (getCurrentNodeLevel(path)>1) {
                        Map<String, Object> currentNode = allNodeMap.get(path);
                        String parentPath = getParentPath(path, currentNode);
                        if (allNodeMap.get(parentPath).containsKey("children")) {
                            List<Map<String, Object>> childrenList = ((List) allNodeMap.get(parentPath).get("children"));
                            boolean childrenExist = false;
                            for (Map<String, Object> children : childrenList) {
                                if(children.get("path").equals(path)) {
                                    childrenExist = true;
                                    break;
                                }
                            }
                            if(childrenExist) {
                                break;
                            }
                            ((List) allNodeMap.get(parentPath).get("children")).add(allNodeMap.get(path));
                            break;
                        }
                        allNodeMap.get(parentPath).put("children", new ArrayList<>());
                        ((List) allNodeMap.get(parentPath).get("children")).add(allNodeMap.get(path));
                        path = parentPath;
                    }
                }
            }
            treeList.clear();
            if(hasRoot) {
                // 从根节点开始取出
                if(compareLeafList) {
                    for (String path : allNodeMap.keySet()) {
                        boolean hasChildren = allNodeMap.get(path).containsKey("children") || allNodeMap.get(path).containsKey(leafArrayName);
                        int level = getCurrentNodeLevel(path);
                        if (level==1 && hasChildren) {
                            treeList.add(allNodeMap.get(path));
                        }
                    }
                } else {
                    for (String path : allNodeMap.keySet()) {
                        int level = getCurrentNodeLevel(path);
                        if (level==1) {
                            treeList.add(allNodeMap.get(path));
                        }
                    }
                }
                return treeList;
            }
            // 从第二级开始取出(如/20/1/,非根节点)
            if(compareLeafList) {
                for (String path : allNodeMap.keySet()) {
                    boolean hasChildren = allNodeMap.get(path).containsKey("children") || allNodeMap.get(path).containsKey(leafArrayName);
                    int level = getCurrentNodeLevel(path);
                    if (path.contains("/") && level==2 && hasChildren) {
                        treeList.add(allNodeMap.get(path));
                    }
                }
            } else {
                for (String path : allNodeMap.keySet()) {
                    int level = getCurrentNodeLevel(path);
                    if (path.contains("/") && level==2) {
                        treeList.add(allNodeMap.get(path));
                    }
                }
            }
            return treeList;
        }
    
        private static int getCurrentNodeLevel(String path) {
            return path.length() - path.replace("/", "").length() - 1;
        }
    
        private static void handleAllNode(Map<String, Map<String, Object>> allNodeMap) {
            // 遍历菜单的path
            for (String nodePath : allNodeMap.keySet()) {
                // 判断是否包含“/”
                // 不包含 -> 是根节点,不处理。continue下一层循环
                // 包含 -> 不是根节点
                int level = getCurrentNodeLevel(nodePath);
                if (level==1) {
                    continue;
                }
                Map<String, Object> currentNode = allNodeMap.get(nodePath);
                // 截取当前最后一级节点之前的路径  /20/1/11/ -> /20/1/
                String parentPath = getParentPath(nodePath, currentNode);
                System.err.println("nodePath"+nodePath);
                System.err.println("currentNode"+currentNode);
                // 如果parentPath不包含"children"这个key,则创建,用于循环判断后放入children
                if (!allNodeMap.get(parentPath).containsKey("children")) {
                    allNodeMap.get(parentPath).put("children", new ArrayList<>());
                }
                String identity = (String) allNodeMap.get(nodePath).get("identity");
                //todo 产品暂时超管平台和社区平台放在一起的。暂时社区平台的权限要去掉物业管理和小区管理
                if (StringUtils.isBlank(identity) || (!identity.equals("propertyManage") && !identity.equals("comManage")) ) {
                    ((List) allNodeMap.get(parentPath).get("children")).add(allNodeMap.get(nodePath));
                }
            }
        }
    
        private static String getParentPath(String nodePath, Map<String, Object> currentNode) {
            return nodePath.substring(0, nodePath.lastIndexOf("/"+ currentNode.get("id") +"/")+1);
        }
    }
    

    Description: 集合工具类

    public class BDCollectionUtils {
    
        // *****************************************************判空**********************************************
    
        /**
         * @param datas
         * @return true表示为空
         * @author Z.H.W
         * @Description:判断所给集合是否为空
         */
        public static <T> boolean isEmpty(Collection<T> datas) {
            return datas == null || datas.isEmpty();
        }
    
        /**
         * @param datas
         * @return true表示不为空
         * @author Z.H.W
         * @Description:判断所给集合是否为空
         */
        public static <T> boolean isNotEmpty(Collection<T> datas) {
            return !isEmpty(datas);
        }
    
        // *****************************************************分组**********************************************
    
        /**
         * @param datas
         * @param unitCount 代表每组的个数
         * @return 返回所有的组
         * @author Z.H.W
         * @Description:按个数分组
         */
        public static <T> List<List<T>> divider(Collection<T> datas, int unitCount) {
            List<List<T>> returnDatas = new ArrayList<List<T>>();
            List<T> unit = null;
            int counter = 0;
            for (T t : datas) {
                if (counter % unitCount == 0) {
                    unit = new ArrayList<T>();
                    returnDatas.add(unit);
                }
                unit.add(t);
                counter++;
            }
            return returnDatas;
        }
    
    
        /**
         * @param datas
         * @param c     是否为同一组的判断标准,相同的数据分为同一组
         * @return
         * @author Z.H.W
         * @Description:按条件分组
         */
        public static <T> List<List<T>> divider(Collection<T> datas, Comparator<? super T> c) {
            List<List<T>> result = new ArrayList<List<T>>();
            for (T t : datas) {
                boolean isSameGroup = false;
                for (int j = 0; j < result.size(); j++) {
                    if (c.compare(t, result.get(j).get(0)) == 0) {
                        isSameGroup = true;
                        result.get(j).add(t);
                        break;
                    }
                }
                if (!isSameGroup) {
                    // 创建
                    List<T> innerList = new ArrayList<T>();
                    result.add(innerList);
                    innerList.add(t);
                }
            }
            return result;
        }
    
        // *****************************************************拼接/并集**********************************************
    
        /**
         * @param datas
         * @return
         * @author Z.H.W
         * @Description:拼接集合
         */
        public static <T, K extends Collection<T>> List<T> contact(Collection<K> datas) {
            List<T> result = new ArrayList<>();
            for (K k : datas) {
                result.addAll(k);
            }
            return result;
        }
    
        /**
         * @param datas
         * @return
         * @author Z.H.W
         * @Description:拼接集合
         */
        public static <T, K extends Collection<T>> List<T> contact(K... datas) {
            return contact(Arrays.asList(datas));
        }
    
        // *****************************************************交集**********************************************
    
        /**
         * @param datas
         * @return
         * @author Z.H.W
         * @Description:集和类求交集
         */
        public static <T, K extends Collection<? extends T>> List<T> intersection(Collection<K> datas) {
            List<T> result = new ArrayList<>();
            Iterator<K> it = datas.iterator();
            if (it.hasNext()) {
                K copy = it.next();
                if (copy != null) {
                    result = new ArrayList<>(copy);
                    for (K k : datas) {
                        result.retainAll(k);
                    }
                }
            }
            return result;
        }
    
        /**
         * @param datas
         * @return
         * @author Z.H.W
         * @Description:集和类求交集
         */
        public static <T, K extends Collection<? extends T>> List<T> intersection(K... datas) {
            return intersection(Arrays.asList(datas));
        }
    
        // *****************************************************差集**********************************************
    
        /**
         * @param a
         * @param b
         * @return A-B
         * @author Z.H.W
         * @Description:求差集
         */
        public static <T, K extends Collection<? extends T>> List<T> sub(K a, K b) {
            List<T> result = new ArrayList<>();
            if (a != null) {
                result = new ArrayList<>(a);
                result.removeAll(b);
            }
            return result;
        }
    
        // *****************************************************判重、查重、去重**********************************************
    
        /**
         * @param datas 需要判断的目标集合
         * @return
         * @author Z.H.W
         * @Description:判重,判断集合中的元素是否有重复元素
         */
        public static boolean isRepeatInCollection(Collection<?> datas) {
            if (datas == null) {// 为空则认为不含重复元素
                return false;
            }
            if (datas instanceof Set) {
                return false;
            }
            Set<?> noRepeatSet = new HashSet<>(datas);
            return !(datas.size() == noRepeatSet.size());
        }
    
        /**
         * @param datas
         * @return
         * @author Z.H.W
         * @Description:查重,找出集合中的重复数据
         */
        public static <T> List<T> findRepeat(Collection<T> datas) {
            if (datas instanceof Set) {
                return new ArrayList<>();
            }
            HashSet<T> set = new HashSet<T>();
            List<T> repeatEles = new ArrayList<T>();
            for (T t : datas) {
                if (set.contains(t)) {
                    repeatEles.add(t);
                } else {
                    set.add(t);
                }
            }
            return repeatEles;
        }
    
        public static <T> int findRepeatObjectSize(Collection<T> datas, T obj) {
            int count = 0;
            if (datas instanceof Set) {
                return count;
            }
            List<T> repeatEles = new ArrayList<T>();
            repeatEles.addAll(datas);
            for (int i = 0; i < repeatEles.size(); i++) {
                if (repeatEles.size() == 0) {
                    break;
                }
                if (((T) repeatEles.get(i)).equals(obj)) {
                    count++;
                    repeatEles.remove(i);
                    i--;
                }
            }
    //        for (T t : datas) {
    //            if (t.equals(obj)) {
    //                count++;
    //            }
    //        }
            return count;
        }
    
        /**
         * @param datas
         * @return List<T> 以list形式返回结果
         * @author Z.H.W
         * @Description:去重,以并转化为List
         */
        public static <T> List<T> distinct(Collection<T> datas) {
            if (datas == null) {
                return new ArrayList<>();
            }
            Set<T> set = null;
            if (datas instanceof Set) {
                return new ArrayList<>(datas);
            } else {
                set = new HashSet<>(datas);
            }
            return new ArrayList<>(set);
        }
    
        // *****************************************************过滤**********************************************
    
        /**
         * @param datas     数据源
         * @param condition 过滤条件
         * @return 返回过滤后的集合
         * @author Z.H.W
         * @Description:过滤集合
         */
        public static <T> List<T> filter(Collection<T> datas, Filter<T> condition) {
            List<T> result = new ArrayList<>();
            if (condition != null) {
                for (T t : datas) {
                    if (condition.pass(t)) {
                        result.add(t);
                    }
                }
            } else {
                return new ArrayList<>(datas);
            }
            return result;
        }
    
        /**
         * 过滤器
         *
         * @param <T>
         * @author puyafeng
         */
        public interface Filter<T> {
            /**
             * 筛选是否通过
             *
             * @param t
             * @return true 表示通过
             */
            boolean pass(T t);
        }
    
    
    }
    

    日期工具类

    package com.pms.tool;
    
    import org.apache.commons.lang3.StringUtils;
    import org.joda.time.*;
    import org.joda.time.format.DateTimeFormat;
    
    import java.time.Duration;
    import java.time.LocalDateTime;
    import java.util.Calendar;
    
    /**
     * <p>Title: BDDateUtils</p>
     * <p>Description: 日期工具类</p>
     * <p>Company: 成都邦道科技有限公司</p>
     *
     * @author zhanghw
     * @date 2020/3/26 4:17 PM
     */
    public class BDDateUtils {
      public static String timezone = "Asia/Shanghai";
      public static final String DATE_FORMAT = "yyyyMMdd";
      public static final String DATE_FORMAT_SPLIT = "yyyy-MM-dd";
      public static final String DATE_FORMAT_CHINESE = "yyyy年MM月dd日";
      public static final String BIRTHDAY_FORMAT = "MMdd";
      public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
      public static final String DATE_TIME_FORMAT_CHINESE = "yyyy年MM月dd日 HH:mm:ss";
      public static final Long MILLS_PER_SECOND = 1000L;
      public static final Long MILLS_PER_HOUR = 60 * 60 * 1000L;
      public static final Long MILLS_PER_DAY = 24 * 60 * 60 * 1000L;
      public static final Long MILLS_PER_MONTH = 30 * 24 * 60 * 60 * 1000L;
      public static final Long MILLS_HALF_MONTH = 15 * 24 * 60 * 60 * 1000L;//半个月
      public static final Long MILLS_OF_TWO_HOURS = 2 * 60 * 60 * 1000L;
      public static final Long MILLS_OF_NINE_HOURS = 9 * 60 * 60 * 1000L;
      public static final long MILLS_PER_MINUTE = 5*60 * 1000L;
      public static final int SECONDS_PER_DAY = 24 * 60 * 60;
      public static final int YEAR_IN_DAYS = 365;
      public static final int WEEK_IN_DAYS = 7;
      public static final int YEAR_IN_MONTHS = 12;
    
      /**
       * 获取当天00:00:00的时间
       * @return
       */
      public static long nowDateInMillis() {
        return nowDate()
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      /**
       * 获取当天00:00:00时刻往后推hour小时的时间
       * @param hour
       * @return
       */
      public static long nowDateInMillsWithHour(int hour) {
        return nowDate()
            .withHourOfDay(hour)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      /**
       * 设置时区
       * @param timezoneId
       */
      public static void setTimeZone(String timezoneId) {
        timezone = timezoneId;
      }
    
      /**
       * 获取beforeDays天前的00:00:00的时间 单位/毫秒
       * @param daysAgo
       * @return
       */
      public static long daysAgoInMillis(int daysAgo) {
        return nowDateInMillis() - MILLS_PER_DAY * daysAgo;
      }
    
      /**
       * 获取afterDays天后的00:00:00的时间 单位/毫秒
       * @param afterDays
       * @return
       */
      public static long daysAfterInMills(int afterDays) {
        return nowDateInMillis() + MILLS_PER_DAY * afterDays;
      }
    
      /**
       * 某个时间往后推afterDays天
       * @param timeStamp
       * @param afterDays
       * @return
       */
      public static long daysAfterInMills(Long timeStamp, int afterDays) {
        return timeStamp + MILLS_PER_DAY * afterDays;
      }
    
      /**
       * 当前时间往前推n个小时
       * @param hoursAgo
       * @return
       */
      public static long hoursAgoInMills(int hoursAgo) {
        return BDDateUtils.now() - MILLS_PER_HOUR * hoursAgo;
      }
    
      /**
       * 某一时间往前推n个小时
       * @param time
       * @param hoursAgo
       * @return
       */
      public static long timeHoursAgoInMills(long time, int hoursAgo) {
        return time - MILLS_PER_HOUR * hoursAgo;
      }
    
      /**
       * 某一时间往后推n个小时
       * @param time
       * @param hoursAfter
       * @return
       */
      public static long timeHoursAfterInMills(long time, int hoursAfter) {
        return time + MILLS_PER_HOUR * hoursAfter;
      }
    
      /**
       * 当前时间往前推n个月
       * @param monthsAgo
       * @return
       */
      public static long monthsAgoInMills(int monthsAgo) {
        return nowDateInMillis() - MILLS_PER_MONTH * monthsAgo;
      }
    
      /**
       * 获取当月第一天的00:00:00时间
       * @return
       */
      public static long nowMonthInMillis() {
        return nowDate()
            .withDayOfMonth(1)
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      /**
       * 获取某个月第一天的00:00:00时间
       * @param timestamp
       * @return
       */
      public static long getMinMillisOfMonth(Long timestamp) {
        return BDDateUtils.getMinMillisOfDay(
            new DateTime(timestamp, getTimeZone())
                .withDayOfMonth(1)
                .getMillis());
      }
    
      /**
       * 获取本月最后一天最后时候
       * @param timestamp
       * @return
       */
      public static long getMaxMillisOfMonth(Long timestamp) {
        return BDDateUtils.getMaxMillisOfDay(
            new DateTime(timestamp, getTimeZone())
                .plusMonths(1)
                .withDayOfMonth(1)
                .minusDays(1)
                .getMillis());
      }
    
      /**
       * 现在到月底所剩时间毫秒数
       * @return
       */
      public static long getRemainingMillisOfMonth() {
        return getMaxMillisOfMonth(now()) - now();
      }
    
      /**
       * 现在到今天结束所剩时间毫秒数
       * @return
       */
      public static long getRemainingMillisOfDay() {
        return getMaxMillisOfDay(now()) - now();
      }
    
      /**
       * 本周第一天开始时间
       * @return
       */
      public static long nowWeekInMillis() {
        return nowDate()
            .withDayOfWeek(1)
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      /**
       * 当前时间毫秒数
       * @return
       */
      public static long now() {
        return nowDate().getMillis();
      }
    
      public static DateTimeZone getTimeZone() {
        return DateTimeZone.forID(timezone);
      }
    
      /**
       * 当前时间DateTime
       * @return
       */
      public static DateTime nowDate() {
        return new DateTime(getTimeZone());
      }
    
      /**
       * 某年起始时刻
       * @param year
       * @return
       */
      public static DateTime dateOfYear(int year) {
        return new DateTime(getTimeZone())
            .withYear(year)
            .withMonthOfYear(1)
            .withDayOfMonth(1)
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0);
      }
    
      /**
       * 毫秒数转化为DataeTime类型
       * @param timestamp
       * @return
       */
      public static DateTime date(Long timestamp) {
        return new DateTime(timestamp, getTimeZone());
      }
    
      /**
       * 获取某天的00:00:00的时间
       * @param timestamp
       * @return
       */
      public static long dateInMills(Long timestamp) {
        return new DateTime(timestamp, getTimeZone())
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      /**
       * 某月第一天开始时间
       * @param timestamp
       * @return
       */
      public static long monthInMills(Long timestamp) {
        return new DateTime(timestamp, getTimeZone())
            .withDayOfMonth(1)
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      /**
       * 某周第一天开始时间
       * @param timestamp
       * @return
       */
      public static long weekInMills(Long timestamp) {
        return new DateTime(timestamp, getTimeZone())
            .withDayOfWeek(1)
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      public static void setDaysAgo(int daysAgo) {
        setCurrentTime();
        DateTimeUtils.setCurrentMillisOffset(-Duration.ofDays(daysAgo).toMillis());
      }
    
      public static void setDaysAfter(int daysAfter) {
        setCurrentTime();
        DateTimeUtils.setCurrentMillisOffset(Duration.ofDays(daysAfter).toMillis());
      }
    
      public static void setDaysAfter(long now, int daysAfter) {
        DateTimeUtils.setCurrentMillisFixed(now + Duration.ofDays(daysAfter).toMillis());
      }
    
      public static void setMinutesAgo(int minutesAgo) {
        setCurrentTime();
        DateTimeUtils.setCurrentMillisOffset(-Duration.ofMinutes(minutesAgo).toMillis());
      }
    
      public static void setMinutesAfter(int minutesAfter) {
        setCurrentTime();
        DateTimeUtils.setCurrentMillisOffset(Duration.ofMinutes(minutesAfter).toMillis());
      }
    
      public static void setMillisAgo(long millisAgo) {
        setCurrentTime();
        DateTimeUtils.setCurrentMillisOffset(-Duration.ofMillis(millisAgo).toMillis());
      }
    
      public static void setMillisAfter(long millisAfter) {
        setCurrentTime();
        DateTimeUtils.setCurrentMillisOffset(Duration.ofMillis(millisAfter).toMillis());
      }
    
      /**
       * 设置系统时间为当前时间
       */
      public static void setCurrentTime() {
        DateTimeUtils.setCurrentMillisSystem();
      }
    
      /**
       * 设置系统时间
       * @param now
       */
      public static void setTime(Long now) {
        DateTimeUtils.setCurrentMillisFixed(now);
      }
    
      public static long getMinMillisOfDay(Long millis) {
        return BDDateUtils.date(millis).millisOfDay().withMinimumValue().getMillis();
      }
    
      //计算天数,计头计尾
      public static int getDaysWithHeadAndTail(long startMillis, long endMills) {
        if (endMills < startMillis) {
          throw new RuntimeException("参数异常,endMills必须不小于startMillis");
        }
        long maxMillisOfFirstDay = getMaxMillisOfDay(startMillis);
        if (maxMillisOfFirstDay > endMills) {
          return 1;
        }
        long leftMillis = endMills - maxMillisOfFirstDay;
        int leftDays = (int) (leftMillis % MILLS_PER_DAY == 0 ? leftMillis / MILLS_PER_DAY : (leftMillis / MILLS_PER_DAY + 1));
        return leftDays + 1;
      }
    
      /**
       * 当天最后时刻时间点
       * @param millis
       * @return
       */
      public static long getMaxMillisOfDay(Long millis) {
        return BDDateUtils.date(millis).millisOfDay().withMaximumValue().getMillis();
      }
    
      public static int getDaysBetween(Long startMillis, Long endMills) {
        return Days.daysBetween(BDDateUtils.date(startMillis), BDDateUtils.date(endMills)).getDays() + 1;
      }
    
      public static int getDaysWithHeadBetween(Long startMillis, Long endMills) {
        if (endMills < startMillis) {
          throw new RuntimeException("参数异常,endMills必须不小于startMillis");
        }
        int days = Days.daysBetween(BDDateUtils.date(startMillis), BDDateUtils.date(endMills)).getDays();
        if (days == 0) {
          days++;
        }
        return days;
      }
    
      public static int getMonthsBetween(Long startMillis, Long endMills) {
        return Months.monthsBetween(BDDateUtils.date(startMillis), BDDateUtils.date(endMills)).getMonths() + 1;
      }
    
      /**
       *
       * @param startMillis
       * @param endMills
       * @return
       * 获取两个日期之间的月数差,不要求月份中的日期
       */
      public static int getRoughMonthsBetween(Long startMillis, Long endMills) {
        if (startMillis > endMills) {
          throw new RuntimeException("参数异常,endMills必须不小于startMillis");
        }
        DateTime startDate = BDDateUtils.date(startMillis);
        DateTime endDate = BDDateUtils.date(endMills);
        return YEAR_IN_MONTHS * (endDate.getYear() - startDate.getYear()) + (endDate.getMonthOfYear() - startDate.getMonthOfYear());
      }
    
      /**
       * 获取两个日期之间的天数差
       */
      public static int getCalenderDaysBetween(Long startMillis, Long endMills) {
        return Days.daysBetween(BDDateUtils.date(BDDateUtils.getMinMillisOfDay(startMillis)),
            BDDateUtils.date(BDDateUtils.getMinMillisOfDay(endMills)))
            .getDays();
      }
    
      /**
       * 两个日期之间的小时差
       * @param startMillis
       * @param endMills
       * @return
       */
      public static int getHoursBetween(Long startMillis, Long endMills) {
        return Hours.hoursBetween(BDDateUtils.date(startMillis), BDDateUtils.date(endMills)).getHours() + 1;
      }
    
      /**
       * 两个日期之间的分钟差
       * @param startMillis
       * @param endMills
       * @return
       */
      public static int getMinutesBetween(Long startMillis, Long endMills) {
        return Minutes.minutesBetween(BDDateUtils.date(startMillis), BDDateUtils.date(endMills)).getMinutes() + 1;
      }
    
      /**
       * 两个日期之间的秒数差
       * @param startMillis
       * @param endMills
       * @return
       */
      public static long getSecondsBetween(Long startMillis, Long endMills) {
        return (endMills - startMillis) / 1000;
      }
    
      /**
       * 到今天结束所剩秒数
       * @return
       */
      public static int getRemainingSecondOfDay() {
        return BDDateUtils.nowDate().secondOfDay().withMaximumValue().getSecondOfDay() - BDDateUtils.nowDate().getSecondOfDay();
      }
    
      /**
       * 字符串毫秒数转化为DateTime类型
       * @param dateStr
       * @return
       */
      public static DateTime jodaDateTimeFromString(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
          return null;
        }
        return BDDateUtils.date(Long.valueOf(dateStr));
      }
    
      /**
       * 世界标准时间日期格式化
       * @param timestamp
       * @return
       */
      public static String utcDateTimeStringFromTimestamp(Long timestamp) {
        if (null == timestamp) {
          return null;
        }
        return new DateTime(timestamp, DateTimeZone.UTC).toString(DateTimeFormat.forPattern(DATE_TIME_FORMAT));
      }
    
      /**
       * 中国时区日期格式化
       * @param timestamp
       * @return
       */
      public static String dateTimeStringFromTimestamp(Long timestamp) {
        return dateTimeStringFromTimestamp(timestamp, DATE_TIME_FORMAT);
      }
    
      /**
       * 根据给定格式,格式化日期
       * @param timestamp
       * @param format
       * @return
       */
    
      public static String dateTimeStringFromTimestamp(Long timestamp, String format) {
        if (null == timestamp) {
          return null;
        }
        return date(timestamp).toString(DateTimeFormat.forPattern(format));
      }
    
      /**
       * 格式化日期 yyyyMMdd
       * @param timestamp
       * @return
       */
      public static String dateString(Long timestamp) {
        return date(timestamp).toString(DATE_FORMAT);
      }
    
      public static String dateString(Long timestamp, String format) {
        return date(timestamp).toString(format);
      }
    
      public static String dateStringChinese(Long timestamp) {
        return date(timestamp).toString(DATE_FORMAT_CHINESE);
      }
    
      public static String dateStringHour(Long timestamp) {
        return date(timestamp).toString("HH:mm:ss");
      }
    
      public static String birthdayString(Long timestamp) {
        return date(timestamp).toString(BIRTHDAY_FORMAT);
      }
    
      /**
       * 解析字符串,转化为日期格式
       * @param dateStr
       * @param format
       * @return
       */
      public static Long dateStringToLong(String dateStr, String format) {
        if (dateStr == null) {
          return 0L;
        }
        long timestampUTC = DateTimeFormat.forPattern(format).withZoneUTC().parseDateTime(dateStr).getMillis();
        int offset = getTimeZone().toTimeZone().getRawOffset();
        return timestampUTC - offset;
      }
    
      public static int dayOfMonth(Long timestamp) {
        return BDDateUtils.date(timestamp).dayOfMonth().get();
      }
    
      public static int hourOfDay(Long timestamp) {
        return BDDateUtils.date(timestamp).hourOfDay().get();
      }
    
      public static int year(long timestamp) {
        return BDDateUtils.date(timestamp).year().get();
      }
    
      public static int monthOfYear(long timestamp) {
        return BDDateUtils.date(timestamp).monthOfYear().get();
      }
    
      public static boolean millisIsDate(long millis) {
        return Long.compare(getMinMillisOfDay(millis), millis) == 0;
      }
    
      public static long sameDayOfMonthsAfter(long millis, int months) {
        return date(millis)
            .plusMonths(months)
            .getMillis();
      }
    
      public static long getHoursBefore(long millis, int hours) {
        return date(millis)
            .minusHours(hours)
            .getMillis();
      }
    
      public static long sameDayOfYearsAfter(long millis, int years) {
        return date(millis)
            .plusYears(years)
            .getMillis();
      }
    
      public static Calendar getCalendar() {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(getTimeZone().toTimeZone());
        return cal;
      }
    
      public static int getDaysOfCurrentMonth(Long currentMonthTimestamp) {
        Calendar cal = getCalendar();
        int currentMonth = date(currentMonthTimestamp).getMonthOfYear();
        cal.set(Calendar.MONTH, currentMonth - 1);
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
      }
    
      public static long nowDateWithHour(int hour) {
        return nowDate()
            .withHourOfDay(hour)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      public static long nowHour() {
        return nowDate()
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      public static long getTimestampWithDayAndHour(Long dayTimestamp, int hour) {
        return date(dayTimestamp)
            .withHourOfDay(hour)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .getMillis();
      }
    
      public static long getDateWithDay(long millis, int day) {
        return date(millis)
            .withDayOfMonth(day)
            .getMillis();
      }
    
      public static int compareDateOnly(long timestamp1, long timestamp2) {
        return DateTimeComparator.getDateOnlyInstance().compare(timestamp1, timestamp2);
      }
    
      public static boolean isWeekend(long timestamp) {
        int weekday = date(timestamp).getDayOfWeek();
        if (weekday > 5) {
          return true;
        } else {
          return false;
        }
      }
    
      public static int getCalenderMonthsBetween(Long startDate, Long endDate) {
        return BDDateUtils.monthOfYear(endDate) + 12 * (BDDateUtils.year(endDate) - BDDateUtils.year(startDate)) - BDDateUtils.monthOfYear(startDate);
      }
    
      public static void main(String[] args) {
    //    DateTime dateTime = dateOfYear(1990);
    //      LocalDateTime.of
    
      }
    

    JSON工具类,在阿里的fastjson基础上封装

    package com.pms.tool;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.parser.ParserConfig;
    import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
    import com.alibaba.fastjson.serializer.SerializeConfig;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    
    import java.io.Serializable;
    import java.util.List;
    import java.util.Map;
    
    /**
     */
    public class BDJsonUtils extends JSON implements Serializable {
    
        private static final SerializeConfig config;
        static {
            config = new SerializeConfig();
            // 使用和json-lib兼容的日期输出格式
            config.put(java.util.Date.class, new JSONLibDataFormatSerializer());
            // 使用和json-lib兼容的日期输出格式
            config.put(java.sql.Date.class, new JSONLibDataFormatSerializer());
    
        }
    
        /**
         * 输出空置字段
         */
        private static final SerializerFeature[] features = {SerializerFeature.WriteMapNullValue,
                // list字段如果为null,输出为[],而不是null
                SerializerFeature.WriteNullListAsEmpty,
                // 数值字段如果为null,输出为0,而不是null
                SerializerFeature.WriteNullNumberAsZero,
                // Boolean字段如果为null,输出为false,而不是null
                SerializerFeature.WriteNullBooleanAsFalse,
                // 字符类型字段如果为null,输出为"",而不是null
                SerializerFeature.WriteNullStringAsEmpty
        };
    
        /**
         * 创建一个json对象
         * @return
         */
        public static JSONObject getFson(){
            return new JSONObject();
        }
    
        public  static JSONArray getFsonArray(){
            return  new JSONArray();
        }
    
        /**
         * 类转json字符串 时间复杂化处理,并且会打印空属性
         * @param object
         * @return
         */
        public static String objToJsonStrWithCF(Object object) {
            return JSON.toJSONString(object, config, features);
        }
        /**
         * 类转json字符串  时间复杂化处理,空属性不会打印 "time":1556449527766,"minutes":5,"seconds":27,"hours":19,"month":3,"year":119,"timezoneOffset":-480,"day":0,"date":28
         * @param object
         * @return
         */
        public static String objToJsonStrWithC(Object object) {
            return JSON.toJSONString(object, config);
        }
    
        /**
         * 类转json字符串   会打印对象中所有的属性,没值的直接为空
         * @param object
         * @return
         */
        public static String objToJsonStrWithF(Object object) {
            return JSON.toJSONString(object);
        }
        /**
         * 推荐使用
         * 类转json字符串  打印对象的所有属性
         * @param object
         * @return
         */
        public static String objToJsonStr(Object object) {
            ParserConfig.getGlobalInstance().setAsmEnable(false);
            return JSON.toJSONString(object,features);
        }
    
    
        /**
         * json字符串转为object类
         * @param text
         * @return
         */
        public static Object strToBean(String text) {
            return JSON.parse(text);
        }
    
        /**
         * json字符串转bean
         * @param text
         * @param clazz
         * @param <T>
         * @return
         */
        public static <T> T strToBean(String text, Class<T> clazz) {
            return JSON.parseObject(text, clazz);
        }
    
        /**
         * json字符串转为数组
         * @param text
         * @param <T>
         * @return
         */
        public static <T> Object[] strToArray(String text) {
            return strToArray(text, null);
        }
    
        /**
         * json字符串转为对象数组
         * @param text
         * @param clazz
         * @param <T>
         * @return
         */
        public static <T> Object[] strToArray(String text, Class<T> clazz) {
            return JSON.parseArray(text, clazz).toArray();
        }
    
        /**
         * json字符串转为 对象集合
         * @param text
         * @param clazz
         * @param <T>
         * @return
         */
        public static <T> List<T> strToList(String text, Class<T> clazz) {
    
            return JSON.parseArray(text, clazz);
        }
    
    
    
        /**
         * 将string转化为序列化的json字符串
         * @return
         */
        public static Object strToJson(String str) {
            Object objectJson  = JSON.parse(str);
            return objectJson;
        }
    
        /**
         * json字符串转化为map
         * @param str
         * @return
         */
        public static <K, V> Map<K, V> strToMap(String str) {
            Map<K, V> m = (Map<K, V>) JSONObject.parseObject(str);
            return m;
        }
    
        /**
         * 转换JSON字符串为对象
         * @param str
         * @param clazz
         * @return
         */
        public static Object strToObject(String str, Class<?> clazz) {
            return JSONObject.parseObject(str, clazz);
        }
    
    
    
        /**
         * 将map转化为string
         * @param map
         * @return
         */
        public static <K, V> String mapToStr(Map<K, V> map) {
            String s = JSONObject.toJSONString(map);
            return s;
        }
    
    
    }
    

    随机数生成工具类

    public class BDRandomUtils {
    
        private static SecureRandom random = new SecureRandom();
    
        private static final String NUMBER_CHAR = "0123456789";
        private static final String LETTER_CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private static final String NUMBER_LOWER_LETTER_CHAR = "0123456789abcdefghijklmnopqrstuvwxyz";
    
        /**
         * 封装JDK自带的UUID, 通过Random数字生成, 中间有-分割.
         */
        public static String uuid() {
            return UUID.randomUUID().toString();
        }
    
        /**
         * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
         */
        public static String uuidNoDelimiter() {
            return UUID.randomUUID().toString().replaceAll("-", "");
        }
    
        /**
         * 使用SecureRandom随机生成${max}以内的int.
         */
        public static int randomInt(int max) {
            return Math.abs(random.nextInt(max));
        }
    
        /**
         * 使用SecureRandom随机生成${min}和${max}之间的int.
         */
        public static int randomInt(int min, int max) {
            return Math.abs(random.nextInt(max - min) + min);
        }
    
        /**
         * 包括数字和字母
         */
        public static String randomStr(int length) {
            return RandomStringUtils.randomAlphanumeric(length);
        }
    
        /**
         * 只包括数字
         *
         * @param length
         * @return
         */
        public static String randomNum(int length) {
            return RandomStringUtils.randomNumeric(length);
        }
    
        /**
         * 只包括字母
         *
         * @param length
         * @return
         */
        public static String randomLetter(int length) {
            return RandomStringUtils.randomAlphabetic(length);
        }
    
        /**
         * 只包括数字和小写字母
         *
         * @param length
         * @return
         */
        public static String randomNumAndLowerLetter(int length) {
            if (length == 0) {
                return "";
            } else if (length < 0) {
                throw new IllegalArgumentException("Requested random string length " + length + " is less than 0.");
            }
            int len = NUMBER_LOWER_LETTER_CHAR.length();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++) {
                sb.append(NUMBER_LOWER_LETTER_CHAR.charAt(randomInt(len)));
            }
            return sb.toString();
        }
    
        public static void main(String[] args) {
            String s = randomNum(6);
            System.out.println(s);
    
        }
    
    }
    

    字符串工具类

    package com.pms.tool;
    
    import java.io.IOException;
    import java.io.Serializable;
    import java.io.UnsupportedEncodingException;
    import java.math.BigDecimal;
    import java.net.URLDecoder;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * <p>Title: BDStringUtil</p>
     * <p>Description: 字符串工具类 </p>
     * <p>Company: 成都邦道科技有限公司</p>
     *
     * @author zhanghw
     * @date 2020/3/26 4:17 PM
     */
    public class BDStringUtil implements Serializable {
    
        /***/
        private static final long serialVersionUID = 1L;
        public static final String DEFAULT_CHART = "UTF-8";
    
        /**
         * 将时间字符串转化为Long型数字
         * @param time HH:mm
         * @return
         */
        public static Long timeStrToLong(String time){
            String str=time.replaceAll(":", "");
            return toLong(str);
        }
    
        /**
         * 过滤空NULL
         * @param o
         * @return
         */
        public static String filterNull(Object o) {
            return o != null && !"null".equals(o.toString()) ? o.toString().trim() : "" ;
        }
    
        /**
         * 是否为空
         * @param o
         * @return
         */
        public static boolean isEmpty(Object o) {
            if (o == null) {
                return true;
            }
            if ("".equals(filterNull(o.toString()))) {
                return true;
            } else {
                return false;
            }
        }
    
        /**
         * 是否不为空
         * @param o
         * @return
         */
        public static boolean isNotEmpty(Object o) {
            if (o == null) {
                return false;
            }
            if ("".equals(filterNull(o.toString()))) {
                return false;
            } else {
                return true;
            }
        }
    
        /**
         * 是否可转化为数字
         * @param o
         * @return
         */
        public static boolean isNumber(Object o) {
            try {
                new BigDecimal(o.toString());
                return true;
            } catch (Exception e) {
            }
            return false;
        }
    
        /**
         * 是否可转化为Long型数字
         * @param o
         * @return
         */
        public static boolean isLong(Object o) {
            try {
                new Long(o.toString());
                return true;
            } catch (Exception e) {
            }
            return false;
        }
    
        /**
         * 转化为Long型数字, 不可转化时返回0
         * @param o
         * @return
         */
        public static Long toLong(Object o) {
            if (isLong(o)) {
                return new Long(o.toString());
            } else {
                return 0L;
            }
        }
    
        /**
         * 转化为int型数字, 不可转化时返回0
         * @param o
         * @return
         */
        public static int toInt(Object o) {
            if (isNumber(o)) {
                return new Integer(o.toString());
            } else {
                return 0;
            }
        }
    
        public static Integer toInteger(Object o) {
            if (isNumber(o)) {
                return new Integer(o.toString());
            } else {
                return null;
            }
        }
    
        /**
         * 替换字符串,支持字符串为空的情形
         * @param strData
         * @param regex
         * @param replacement
         * @return
         */
        public static String replace(String strData, String regex, String replacement) {
            return strData == null ? "" : strData.replaceAll(regex, replacement);
        }
    
        /**
         * 字符串转为HTML显示字符
         * @param strData
         * @return
         */
        public static String string2HTML(String strData){
            if( strData == null || "".equals(strData) ){
                return "" ;
            }
            strData = replace(strData, "&", "&amp;");
            strData = replace(strData, "<", "&lt;");
            strData = replace(strData, ">", "&gt;");
            strData = replace(strData, "\"", "&quot;");
            return strData;
        }
    
        /**
         * 从指定位置截取指定长度的字符串
         * @param
         * @return
         */
        public static String getMiddleString(String input, int index, int count) {
            if (isEmpty(input)) {
                return "";
            }
            count = (count > input.length() - index + 1) ? input.length() - index + 1 : count;
            return input.substring(index - 1, index + count - 1);
        }
    
        /**
         * 将"/"替换成"\"
         * @param strDir
         * @return
         */
        public static String changeDirection(String strDir) {
            String s = "/";
            String a = "\\";
            if (strDir != null && !" ".equals(strDir)) {
                if (strDir.contains(s)) {
                    strDir = strDir.replace(s, a);
                }
            }
            return strDir;
        }
    
        /**
         * 去除字符串中 头和尾的空格,中间的空格保留
         *
         * @Title: trim
         * @Description: TODO
         * @return String
         * @throws
         */
        public static String trim(String s) {
            int i = s.length();// 字符串最后一个字符的位置
            int j = 0;// 字符串第一个字符
            int k = 0;// 中间变量
            char[] arrayOfChar = s.toCharArray();// 将字符串转换成字符数组
            while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
                ++j;// 确定字符串前面的空格数
            while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
                --i;// 确定字符串后面的空格数
            return (((j > 0) || (i < s.length())) ? s.substring(j, i) : s);// 返回去除空格后的字符串
        }
    
        /**
         * 得到大括号中的内容
         * @param str
         * @return
         */
        public static String getBrackets(String str) {
            int a = str.indexOf("{");
            int c = str.indexOf("}");
            if (a >= 0 && c >= 0 & c > a) {
                return (str.substring(a + 1, c));
            } else {
                return str;
            }
        }
    
        /**
         * 去掉字符串中、前、后的空格
         * @param  args
         * @throws IOException
         */
        public static String extractBlank(String name) {
            if (name != null && !"".equals(name)) {
                return name.replaceAll(" +", "");
            } else {
                return name;
            }
        }
    
        /**
         * 将null换成""
         * @param str
         * @return
         */
        public static String convertStr(String str) {
            return str != null && !"null".equals(str) ? str.trim() : "";
        }
    
        /**
         * 字符串转换unicode
         */
        public static String string2Unicode(String string) {
            StringBuffer unicode = new StringBuffer();
            for (int i = 0; i < string.length(); i++) {
                // 取出每一个字符
                char c = string.charAt(i);
                // 转换为unicode
                unicode.append("\\u" + Integer.toHexString(c));
            }
            return unicode.toString();
        }
        /**
         * unicode 转字符串
         */
        public static String unicode2String(String unicode) {
            StringBuffer string = new StringBuffer();
            String[] hex = unicode.split("\\\\u");
            for (int i = 1; i < hex.length; i++) {
                // 转换出每一个代码点
                int data = Integer.parseInt(hex[i], 16);
                // 追加成string
                string.append((char) data);
            }
            return string.toString();
        }
        /**
         *
         * TODO URL转换为参数字符串
         * 如 "index.jsp?id=123&code=tom",解析为id=123&code=tom
         * @author MrXiao
         * @date 2017年4月27日 上午11:24:23
         * @param url
         * @return
         */
        public static String truncateUrlPage(String url) {
            if (url == null) {
                return null;
            }
            url = url.trim().toLowerCase();
    
            if (url.contains("?")) {
                String[] arrSplit = url.split("[?]");
                if (arrSplit.length > 1) {
                    if (arrSplit[1] != null) {
                        return arrSplit[1];
                    }
                }
            }
            return url;
        }
    
        /**
         *
         * TODO URL参数转换为Map
         * id=123&code=tom转换为Map
         * @author MrXiao
         * @date 2017年4月27日 上午11:28:10
         * @param urlParamStr
         * @return
         */
        public static Map<String, String> urlParam(String urlParamStr){
            Map<String, String> map = new HashMap<String, String>();
            String strUrlParam = truncateUrlPage(urlParamStr);
            if (strUrlParam == null) {
                return map;
            }
            // 每个键值为一组
            String[] arrSplit = strUrlParam.split("[&]");
            for (String strSplit : arrSplit) {
                String[] arrSplitEqual = strSplit.split("[=]");
    
                // 解析出键值
                if (arrSplitEqual.length > 1) {
                    if(arrSplitEqual[1] != null && arrSplitEqual[1].contains("%")){
                        // 正确解析
                        try {
                            map.put(arrSplitEqual[0], URLDecoder.decode(arrSplitEqual[1], "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        // 正确解析
                        map.put(arrSplitEqual[0], trim(arrSplitEqual[1]));
                    }
                } else {
                    if (arrSplitEqual[0] != "") {
                        // 只有参数没有值,不加入
                        map.put(arrSplitEqual[0], "");
                    }
                }
            }
            return map;
        }
    
    
        /**
         * @see #join(Object[] array, String sep, String prefix)
         */
        public static String join(Object[] array, String sep) {
            return join(array, sep, null);
        }
    
        /**
         * @see #join(Object[] array, String sep, String prefix)
         */
        public static String join(Collection<?> list, String sep) {
            return join(list, sep, null);
        }
    
        /**
         * @see #join(Object[] array, String sep, String prefix)
         */
        public static String join(Collection<?> list, String sep, String prefix) {
            Object[] array = list == null ? null : list.toArray();
            return join(array, sep, prefix);
        }
    
        /**
         * 以指定的分隔符来进行字符串元素连接
         * <p>
         * 例如有字符串数组array和连接符为逗号(,)
         * <code>
         * String[] array = new String[] { "hello", "world", "qiniu", "cloud","storage" };
         * </code>
         * 那么得到的结果是:
         * <code>
         * hello,world,qiniu,cloud,storage
         * </code>
         * </p>
         *
         * @param array  需要连接的对象数组
         * @param sep    元素连接之间的分隔符
         * @param prefix 前缀字符串
         * @return 连接好的新字符串
         */
        public static String join(Object[] array, String sep, String prefix) {
            if (array == null) {
                return "";
            }
    
            int arraySize = array.length;
    
            if (arraySize == 0) {
                return "";
            }
    
            if (sep == null) {
                sep = "";
            }
    
            if (prefix == null) {
                prefix = "";
            }
    
            StringBuilder buf = new StringBuilder(prefix);
            for (int i = 0; i < arraySize; i++) {
                if (i > 0) {
                    buf.append(sep);
                }
                buf.append(array[i] == null ? "" : array[i]);
            }
            return buf.toString();
        }
    
        /**
         * 以json元素的方式连接字符串中元素
         * <p>
         * 例如有字符串数组array
         * <code>
         * String[] array = new String[] { "hello", "world", "qiniu", "cloud","storage" };
         * </code>
         * 那么得到的结果是:
         * <code>
         * "hello","world","qiniu","cloud","storage"
         * </code>
         * </p>
         *
         * @param array 需要连接的字符串数组
         * @return 以json元素方式连接好的新字符串
         */
        public static String jsonJoin(String[] array) {
            int arraySize = array.length;
            int bufSize = arraySize * (array[0].length() + 3);
            StringBuilder buf = new StringBuilder(bufSize);
            for (int i = 0; i < arraySize; i++) {
                if (i > 0) {
                    buf.append(',');
                }
    
                buf.append('"');
                buf.append(array[i]);
                buf.append('"');
            }
            return buf.toString();
        }
    
        public static boolean isNullOrEmpty(String s) {
            return s == null || "".equals(s);
        }
    
        public static boolean inStringArray(String s, String[] array) {
            for (String x : array) {
                if (x.equals(s)) {
                    return true;
                }
            }
            return false;
        }
    
        public static byte[] utf8Bytes(String data) {
            try {
                return data.getBytes(DEFAULT_CHART);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    
        public static String utf8String(byte[] data) {
            try {
                return new String(data, DEFAULT_CHART);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    
        public static boolean isBlank(String value) {
            int strLen;
            if (value == null || (strLen = value.length()) == 0) {
                return true;
            }
            for (int i = 0; i < strLen; i++) {
                if ((Character.isWhitespace(value.charAt(i)) == false)) {
                    return false;
                }
            }
            return true;
        }
    
        public static boolean isBlankLoop(String ...values) {
            int strLen;
            if (values == null || (strLen = values.length) == 0) {
                return true;
            }
            for (String value: values
            ) {
                if (value == null || (strLen = value.length()) == 0) {
                    continue;
                }
                for (int i = 0; i < strLen; i++) {
                    if ((Character.isWhitespace(value.charAt(i)) == false)) {
                        return false;
                    }
                }
            }
            return true;
        }
    
        public static boolean isNotBlank(String value) {
            return !isBlank(value);
        }
    
        public static boolean isNotBlankLoop(String ...values) {
            return !isBlankLoop(values);
        }
    
        /**
         * 检查指定的字符串列表是否不为空。
         */
        public static boolean areNotEmpty(String... values) {
            boolean result = true;
            if (values == null || values.length == 0) {
                result = false;
            } else {
                for (String value : values) {
                    result &= !isEmpty(value);
                }
            }
            return result;
        }
    
        /**
         * 首字母大写
         * @param str
         * @return
         */
        public static String getFirstUpper(String str) {
            String newStr = "";
            if (str.length() > 0) {
                newStr = str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
            }
            return newStr;
        }
    
        /**
         *  将驼峰命名的字符串转成符合数据库字段的字符串
         *@Author hufei 2020/4/13
         *@param  str
         *@return java.lang.String
         *
         */
        public static String getColunm(String str) {
            if(isEmpty(str)) {
                return str;
            }
            char[] chars = str.toCharArray();
            //
            for (char c : chars) {
                if(c>65 && c<90) {
                    String[] strArry = str.split(String.valueOf(c));
                    str = strArry[0]+"_"+String.valueOf(c)+getColunm(strArry[1]);
                }
            }
            return str.toUpperCase();
    
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值