Bootstrap

工具类集合

校验数字

private Boolean validateNumber(String num) {
        //验证是否是数值类型
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        return pattern.matcher(num).matches();
    }

正则校验日期

private Boolean validateData(String saleDate) {
        String eL = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";

        //验证是否是日期类型
        Pattern pattern = Pattern.compile(eL);
        return pattern.matcher(saleDate).matches();
    }

object 转换为 List

public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

格式化BigDecimal类型的值,小数点后面无用的0

public BigDecimal stripTrailingZeros(BigDecimal value) {
        final DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        return new BigDecimal(decimalFormat.format(value));
    }

生成随机码

public static String randomCode(int engCode) {
        //声明一个StringBuffer存储随机数
        StringBuffer sb = new StringBuffer();
        char[] englishCodeArray =
                {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4',
                        '5', '6', '7', '8', '9'};
        Random random = new Random();
        //获取英文
        for (int i = 0; i < engCode; i++) {
            char num = englishCodeArray[random.nextInt(englishCodeArray.length)];
            sb.append(num);
        }
        return sb.toString();
    }

替换JSONObject的key值

	//调用,formData是被替换的json,map是要替换的key值(原理:重组json)
    //jsonObj = changeJsonObj(jsonObject, hashedMap);
    public static JSONObject changeJsonObj(JSONObject jsonObj, Map<String, String> keyMap) {
        JSONObject json = new JSONObject();
        //获取json的key
        Set<String> keySet = jsonObj.keySet();
        for (String key : keySet) {
            //当前key在map的中为空,key是json的key,不为空是map的key(目标key)
            String newKey = keyMap.get(key) == null ? key : keyMap.get(key);
            try {
                JSONObject jsonObject = jsonObj.getJSONObject(key);
                //以防父级不用替换,子级要替换时的递归
                json.put(newKey, changeJsonObj(jsonObject, keyMap));
            } catch (Exception e) {
                try {
                    //当前json是array,进行array的重组,不是则catch
                    JSONArray jsonArr = jsonObj.getJSONArray(key);
                    json.put(newKey, changeJsonArr(jsonArr, keyMap));
                } catch (Exception x) {
                    //重组json的key和value
                    json.put(newKey, jsonObj.get(key));
                    if (newKey.equals("label")){
                        json.put("text",jsonObj.get(key));
                    }
                }
            }
        }
        return json;
    }

    public static JSONArray changeJsonArr(JSONArray jsonArr, Map<String, String> keyMap) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < jsonArr.size(); i++) {
            JSONObject jsonObj = jsonArr.getJSONObject(i);
            //将一个jsonarray当成一个object进行替换
            jsonArray.add(changeJsonObj(jsonObj, keyMap));
            //替换完成后,add,return
        }
        return jsonArray;
    }

字符串转为拼音工具类

public class PinyinUtils {

    private static final Logger LOG = LoggerFactory.getLogger(PinyinUtils.class);

    /**
     * 获得汉语拼音首字母(大写拼音首字母)
     *
     * @param chines 汉字
     * @return
     */
    public static String getAlpha(String chines) {
        chines = cleanChar(chines);
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }

    /**
     * 将字符串中的中文转化为拼音,英文字符不变
     *
     * @param inputString 汉字
     * @return
     */
    public static String getPingYin(String inputString) {
        inputString = cleanChar(inputString);
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        String output = "";
        if (inputString != null && inputString.length() > 0 && !"null".equals(inputString)) {
            char[] input = inputString.trim().toCharArray();
            try {
                for (int i = 0; i < input.length; i++) {
                    if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
                        output += temp[0];
                    } else
                        output += java.lang.Character.toString(input[i]);
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        } else {
            return "*";
        }
        return output;
    }

    /**
     * 汉字转换位汉语拼音首字母,英文字符不变
     *
     * @param chines 汉字
     * @return 拼音
     */
    public static String converterToFirstSpell(String chines) {
        chines = cleanChar(chines);
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }

    /**
     * 清理特殊字符以便得到
     *
     * @param chines
     * @return
     */
    public static String cleanChar(String chines) {
        chines = chines.replaceAll("[\\p{Punct}\\p{Space}]+", ""); // 正则去掉所有字符操作
        // 正则表达式去掉所有中文的特殊符号
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}<>《》【】‘;:”“’。,、?]";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(chines);
        chines = matcher.replaceAll("").trim();
        return chines;
    }

    /**
     * 得到中文首字母
     *
     * @param str 需要转化的中文字符串
     * @return String
     */
    public static String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += Character.toUpperCase(pinyinArray[0].charAt(0));
            } else {
                convert += word;
            }
        }
        return convert;
    }

}

计算奖品中奖概率

@Data
public class LotteryDTO implements Serializable {
    /**
     * 中奖数字范围起点(通常0作为起点)
     */
    private Integer winningStartCode;
    /**
     * 当前概率计算出的中奖数字范围终点
     */
    private Integer winningEndCode;

    /**
     * 中奖的数字范围
     */
    private Integer codeScope;
}
@Data
public class LotteryItemDTO implements Serializable {
    //主键id
    private Long id;
    //奖品名称
    private String name;
    //类型:0.现金 1.实物 2.谢谢参与
    private Integer type;
    //金额
    private BigDecimal money;
    //库存
    private Integer stock;
    //中奖率
    private Double probability;
    //奖品中奖数字范围起点
    private Integer awardStartCode;
    //奖品中奖数字范围终点
    private Integer awardEndCode;
    //中奖数字
    private Integer awardCode;
}

核心代码

private void calAwardProbability(LotteryDTO dto, List<LotteryItemDTO> lotteryItemList) {
        Integer codeScope = 1;
        for (LotteryItemDTO item : lotteryItemList) {
            Integer nowScope = 1;
            Double probability = item.getProbability();
            while (true) {
                Double awardProbability = probability * nowScope;
                // 概率的精确度,调整到小数点后10位,概率太小等于不中奖,跳出
                if (awardProbability < 0.0000000001) {
                    break;
                }
                if ((awardProbability >= 1L && (awardProbability - awardProbability.longValue()) < 0.0001D) || nowScope >= MAX_SOPE) {
                    if (nowScope > codeScope) {
                        // 设置中奖范围
                        codeScope = nowScope;
                    }
                    break;
                } else {
                    // 中奖数字范围以10倍进行增长
                    nowScope = nowScope * 10;
                }
            }
        }
        Integer winningStartCode = 0;
        Integer winningEndCode = winningStartCode;
        for (LotteryItemDTO item : lotteryItemList) {
            Integer codeNum = (int) (item.getProbability() * codeScope); // 获得其四舍五入的整数值
            // 无人中奖时,将中奖的起始范围设置在随机数的范围之外
            if (codeNum == 0) {
                item.setAwardStartCode(codeScope + 1);
                item.setAwardEndCode(codeScope + 1);
            } else {
                item.setAwardStartCode(winningEndCode);
                item.setAwardEndCode(winningEndCode + codeNum - 1);
                winningEndCode = winningEndCode + codeNum;
            }
        }
        // 设置用户的中奖随机码信息
        dto.setWinningStartCode(winningStartCode);
        dto.setWinningEndCode(winningEndCode);
        dto.setCodeScope(codeScope);
    }

    //开始抽奖
    private LotteryItemDTO beginLottery(LotteryDTO lottery, List<LotteryItemDTO> lotteryItemList) {
        Integer randomCode = random.nextInt(lottery.getCodeScope());
        if (randomCode >= lottery.getWinningStartCode() && randomCode <= lottery.getWinningEndCode()) {
            for (LotteryItemDTO item : lotteryItemList) {
                if (randomCode >= item.getAwardStartCode() && randomCode <= item.getAwardEndCode()) {
                    item.setAwardCode(randomCode);
                    return item;
                }
            }
        }
        return null;
    }

上传CSV文件工具类

@Slf4j
public class CsvImportUtil {

    /**
     * @return File  一般文件类型
     * @Description 上传文件的文件类型
     * @Param multipartFile
     **/
    public static File uploadFile(MultipartFile multipartFile) {
        // 获 取上传 路径
        String path = BladexConfig.getCsvProfile() + "/" + DateUtils.datePath() + "/" + SecurityUtils.getUsername() + DateUtils.dateTimeNow() + multipartFile.getOriginalFilename();
        try {
            // 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
            File file = new File(path);
            // 此抽象路径名表示的文件或目录是否存在
            if (!file.getParentFile().exists()) {
                // 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录
                file.getParentFile().mkdirs();
            }
            // 转换为一般file 文件
            multipartFile.transferTo(file);

            return file;
        } catch (IOException e) {

            e.printStackTrace();
            return null;
        }

    }

    /**
     * @return List<List < String>>
     * @Description 读取CSV文件的内容(不含表头)
     * @Param filePath 文件存储路径,colNum 列数
     **/
    public static List<List<String>> readCSV(String filePath, int colNum) {
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream(filePath);
            inputStreamReader = new InputStreamReader(fileInputStream, getCharset(filePath));//自动识别
            //inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            bufferedReader = new BufferedReader(inputStreamReader);

            CSVParser parser = CSVFormat.DEFAULT.parse(bufferedReader);


            //  表内容集合,外层 List为行的集合,内层 List为字段集合
            List<List<String>> values = new ArrayList<>();


            int rowIndex = 0;
            // 读取文件每行内容

            for (CSVRecord record : parser.getRecords()) {
                //  跳过表头
                if (rowIndex == 0) {
                    rowIndex++;
                    continue;
                }
                // 判断下角标是否越界
                if (colNum > record.size()) {
                    // 返回空集合
                    return values;
                }
                //  每行的内容
                List<String> value = new ArrayList<>();
                for (int i = 0; i < colNum; i++) {
                    value.add(record.get(i));
                }
                values.add(value);
                rowIndex++;
            }
            return values;
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            //关闭流
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String getCharset(String filePath) {
        String charset = null;
        try {
            charset = getCharset(new FileInputStream(filePath));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
        log.info("文件[" + filePath + "] 采用的字符集为: [" + charset + "]");
        return charset;
    }

    public static String getCharset(InputStream inputStream) {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        try {
            boolean checked = false;
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1) {
                bis.close();
                return charset; // 文件编码为 ANSI
            } else if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE"; // 文件编码为 Unicode
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
                charset = "UTF-16BE"; // 文件编码为 Unicode big endian
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8"; // 文件编码为 UTF-8
                checked = true;
            }
            bis.reset();
            if (!checked) {
                while ((read = bis.read()) != -1) {
                    if (read >= 0xF0)
                        break;
                    if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
                        break;
                    if (0xC0 <= read && read <= 0xDF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
                            // (0x80 - 0xBF),也可能在GB编码内
                            continue;
                        else
                            break;
                    } else if (0xE0 <= read && read <= 0xEF) { // 也有可能出错,但是几率较小
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
            }
            bis.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (null != inputStream) inputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        log.info("文件采用的字符集为: [" + charset + "]");
        return charset;
    }


}

导入文件并下载excel

public void checkPddBuyPrice(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws Exception {
        List<CheckPddPriceVO> list = apiService.checkPddBuyPrice(file);
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet1 = workbook.createSheet("分区信息一");
        HSSFRow row = sheet1.createRow(0);
        row.createCell(0).setCellValue("订单号");
        row.createCell(1).setCellValue("买入价格");
        row.createCell(2).setCellValue("实付总价格");
        for (CheckPddPriceVO e : list) {
            int lastRowNum = sheet1.getLastRowNum();
            HSSFRow lastRow = sheet1.createRow(lastRowNum + 1);
            lastRow.createCell(0).setCellValue(e.getOrderId());
            lastRow.createCell(1).setCellValue(e.getBuyPrice().toString());
            lastRow.createCell(2).setCellValue(e.getRealBuyPrice().toString());
        }
        String filename = "手动校验.xls";
        filename = URLEncoder.encode(filename, "utf-8").replace("+", " ");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType(request.getServletContext().getMimeType(filename));
        //下载输出流
        workbook.write(response.getOutputStream());
    }

解析省市区地址工具类

public class AddressResolutionUtils {

    //解析省市区
    public static JSONObject addressResolution(String address) {
        String regex = "(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<county>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
        Matcher m = Pattern.compile(regex).matcher(address);
        String province = null, city = null, county = null, town = null, village = null;
        JSONObject row = new JSONObject();
        while (m.find()) {
            province = m.group("province");
            row.put("province", province == null ? "" : province.trim());
            city = m.group("city");
            row.put("city", city == null ? "" : city.trim());
            county = m.group("county");
            row.put("county", county == null ? "" : county.trim());
            town = m.group("town");
            town = town == null ? "" : town.trim();
            row.put("town", town);
            village = m.group("village");
            village = village == null ? "" : village.trim();
            row.put("village", village);
            row.put("address", town + village);
        }
        return row;
    }

}

手机号校验工具类

public class PhoneUtil {

    /**
     * ^ 匹配输入字符串开始的位置
     * \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d
     * $ 匹配输入字符串结尾的位置
     */
    public static final String CHINA_REGEX_EXP = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[0-9])|(18[0-9])|(19[1,8,9]))\\d{8}$";
    public static final String HK_REGEX_EXP = "^(5|6|8|9)\\d{7}$";


    /**
     * 校验是否为大陆号码或香港号码
     *
     * @param str
     * @return 符合规则返回true
     */
    public static boolean isPhoneNum(String str) throws Exception {
        return isChinaPhoneNum(str) || isHkPhoneNum(str);
    }

    /**
     * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
     * 此方法中前三位格式有:
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4,这样的话字母也会被认为是正确的)
     * 166
     * 17+任意数
     * 18+任意数
     * 198,199
     *
     * @param str
     * @return 正确返回true
     */
    public static boolean isChinaPhoneNum(String str) throws Exception {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d
        // $ 匹配输入字符串结尾的位置
        Pattern p = Pattern.compile(CHINA_REGEX_EXP);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 香港手机号码8位数,5|6|8|9开头+7位任意数
     *
     * @param str
     * @return 正确返回true
     */
    public static boolean isHkPhoneNum(String str) throws Exception {
        Pattern p = Pattern.compile(HK_REGEX_EXP);
        Matcher m = p.matcher(str);
        return m.matches();
    }

}

生成二维码工具类

@Slf4j
public class QRCodeUtils {
    public static String getQrcode(String content) {
        QrConfig config = new QrConfig(300, 300);
        // 设置边距,既二维码和背景之间的边距
        config.setMargin(1);
        // 设置前景色,既二维码颜色(青色)
       /* config.setForeColor(Color.CYAN.getRGB());
        // 设置背景色(灰色)
        config.setBackColor(Color.GRAY.getRGB());*/
        BufferedImage image = QrCodeUtil.generate(content, config);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            log.error("生成二维码失败: {}", e.getMessage());
        }
        String encode = "data:image/png;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());
        return encode;
    }
}

随机数生成工具类

public class RandomUtil {
    private static final String SYMBOLS = "0123456789"; // 纯数字
    private static final Random RANDOM = new SecureRandom();

    //设置生成多少位的随机数
    public static String getRandomNum(int num) {
        char[] nonceChars = new char[num];  //指定长度,自己可以设置

        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }
}

如果有会继续更新。。。。。

;