1. 集合
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class CollectionUtils {
public static List<Long> transforString2ListLong(String param) {
ArrayList<Long> results = new ArrayList<>();
if (StringUtils.isBlank(param)) {
return results;
}
String[] classArray = param.split(",");
for (int i = 0; i < classArray.length; i++) {
if (StringUtils.isBlank(classArray[i])) {
return results;
}
results.add(Long.valueOf(classArray[i]));
}
return results;
}
public static List<String> transforString2ListString(String param) {
ArrayList<String> results = new ArrayList<>();
if (StringUtils.isBlank(param)) {
return results;
}
String[] classArray = param.split(",");
for (int i = 0; i < classArray.length; i++) {
if (StringUtils.isBlank(classArray[i])) {
return results;
}
results.add(classArray[i]);
}
return results;
}
}
2. 加解密
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class AesUtil {
private static String iv = "12db76f678b0f72e";
private static String Algorithm = "AES";
private static String AlgorithmProvider = "AES/CBC/PKCS5Padding";
public static String encrypt(String src, String uniqueKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
byte[] key = uniqueKey.getBytes();
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] cipherBytes = cipher.doFinal(src.getBytes("UTF-8"));
return byteToHexString(cipherBytes);
}
public static String decrypt(String enc, String uniqueKey) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidAlgorithmParameterException, InvalidKeyException, DecoderException, BadPaddingException, IllegalBlockSizeException {
byte[] key = uniqueKey.getBytes();
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] hexBytes = hexStringToBytes(enc);
byte[] plainBytes = cipher.doFinal(hexBytes);
return new String(plainBytes, "UTF-8");
}
private static String byteToHexString(byte[] src) {
return Hex.encodeHexString(src);
}
private static byte[] hexStringToBytes(String hexString) throws DecoderException {
return Hex.decodeHex(hexString);
}
public static void main(String[] args) {
try {
String uniqueKey = "a6a562023a7e4104a17282a513081ad9";
String src = "330102201504083125";
System.out.println("密钥:" + uniqueKey);
System.out.println("原字符串:" + src);
String encrypt = encrypt(src, uniqueKey);
System.out.println("加密:" + encrypt);
String decrypt = decrypt(encrypt, uniqueKey);
System.out.println("解密:" + decrypt);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
3. 地址解析
import cn.authing.core.types.S;
import com.alibaba.fastjson.JSONObject;
import java.time.Year;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AddressResolutionUtil {
public static String addressResolution(String address) {
address = address.replaceAll("[\\s,,]+", "");
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;
List<Map<String, String>> table = new ArrayList<Map<String, String>>();
Map<String, String> row = null;
while (m.find()) {
row = new LinkedHashMap<String, String>();
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");
row.put("town", town == null ? "" : town.trim());
village = m.group("village");
row.put("village", village == null ? "" : village.trim());
table.add(row);
}
if (table.size() == 0) {
return ",,," + address;
}
Map<String, String> stringMap = table.get(0);
String pr = stringMap.get("province");
String ci = stringMap.get("city");
String co = stringMap.get("county");
String to = stringMap.get("town");
String vi = stringMap.get("village");
return pr + "," + ci + "," + co + "," + to + "," + vi;
}
public static void main(String[] args) {
System.out.println(addressResolution("浙江,省杭州市钱,塘区,白杨街道像之素公寓19幢3单元802室"));
}
}
3. 汉字->拼音转化
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChineseCharacterUtil {
public static String convertHanzi2Pinyin(String hanzi, boolean full) {
String regExp = "^[\u4E00-\u9FFF]+$";
StringBuffer sb = new StringBuffer();
if (hanzi == null || "".equals(hanzi.trim())) {
return "";
}
String pinyin = "";
for (int i = 0; i < hanzi.length(); i++) {
char unit = hanzi.charAt(i);
if (match(String.valueOf(unit), regExp))
{
pinyin = convertSingleHanzi2Pinyin(unit);
if (full) {
sb.append(pinyin);
} else {
sb.append(pinyin.charAt(0));
}
} else {
sb.append(unit);
}
}
return sb.toString();
}
private static String convertSingleHanzi2Pinyin(char hanzi) {
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
String[] res;
StringBuffer sb = new StringBuffer();
try {
res = PinyinHelper.toHanyuPinyinStringArray(hanzi, outputFormat);
sb.append(res[0]);
} catch (Exception e) {
e.printStackTrace();
return "";
}
return sb.toString();
}
public static boolean match(String str, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.find();
}
public static void main(String[] args) {
System.out.println(convertHanzi2Pinyin("我是中国人123abc", true));
}
}
4. 版本号(日期)生成
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class VersionSortUtils {
public static String getUpdateVerSion() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(new Date());
return format;
}
}
5. 代码生成器
package com.hx.utils;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CodeGeneratorUtil {
public static final String DB_URL = "jdbc:mysql://1287.0.0.1/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
public static final String DB_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
public static final String BASE_PACKAGE_PATH = "com.hx";
public static final String USERNAME = "root";
public static final String PASSWORD = "123456";
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void execute() {
AutoGenerator mpg = new AutoGenerator();
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("WTT");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(CodeGeneratorUtil.DB_URL);
dsc.setDriverName(CodeGeneratorUtil.DB_DRIVER_NAME);
dsc.setUsername(USERNAME);
dsc.setPassword(PASSWORD);
mpg.setDataSource(dsc);
PackageConfig pc = new PackageConfig();
pc.setParent(CodeGeneratorUtil.BASE_PACKAGE_PATH);
mpg.setPackageInfo(pc);
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
}
};
String templatePath = "/templates/mapper.xml.ftl";
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setRestControllerStyle(true);
strategy.setEntityLombokModel(true);
strategy.setControllerMappingHyphenStyle(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
public static void main(String[] args) {
execute();
}
}
6. 复制表格
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class CopyExcelUtil {
public static boolean copyExcel(String tmpExcel, String newFile) {
File fi = new File(newFile);
if (!fi.exists()) {
try {
fi.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fis = null;
XSSFWorkbook wb = null;
try {
fis = new FileInputStream(tmpExcel);
wb = new XSSFWorkbook(fis);
OutputStream out = new FileOutputStream(newFile);
wb.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
7. 身份证校验
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;
@SuppressWarnings({"unchecked", "unused", "all"})
public class IdcardValidatorUtils {
protected String codeAndCity[][] = {{"11", "北京"}, {"12", "天津"},
{"13", "河北"}, {"14", "山西"}, {"15", "内蒙古"}, {"21", "辽宁"},
{"22", "吉林"}, {"23", "黑龙江"}, {"31", "上海"}, {"32", "江苏"},
{"33", "浙江"}, {"34", "安徽"}, {"35", "福建"}, {"36", "江西"},
{"37", "山东"}, {"41", "河南"}, {"42", "湖北"}, {"43", "湖南"},
{"44", "广东"}, {"45", "广西"}, {"46", "海南"}, {"50", "重庆"},
{"51", "四川"}, {"52", "贵州"}, {"53", "云南"}, {"54", "西藏"},
{"61", "陕西"}, {"62", "甘肃"}, {"63", "青海"}, {"64", "宁夏"},
{"65", "新疆"}, {"71", "台湾"}, {"81", "香港"}, {"82", "澳门"},
{"91", "国外"}};
private String cityCode[] = {"11", "12", "13", "14", "15", "21", "22",
"23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43",
"44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63",
"64", "65", "71", "81", "82", "91"};
private int power[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
private String verifyCode[] = {"1", "0", "X", "9", "8", "7", "6", "5",
"4", "3", "2"};
public boolean isValidatedAllIdcard(String idcard) {
if (idcard.length() == 15) {
idcard = this.convertIdcarBy15bit(idcard);
}
return this.isValidate18Idcard(idcard);
}
public boolean isValidate18Idcard(String idcard) {
if (idcard.length() != 18) {
return false;
}
String idcard17 = idcard.substring(0, 17);
String idcard18Code = idcard.substring(17, 18);
char c[] = null;
String checkCode = "";
if (isDigital(idcard17)) {
c = idcard17.toCharArray();
} else {
return false;
}
if (null != c) {
int bit[] = new int[idcard17.length()];
bit = converCharToInt(c);
int sum17 = 0;
sum17 = getPowerSum(bit);
checkCode = getCheckCodeBySum(sum17);
if (null == checkCode) {
return false;
}
if (!idcard18Code.equalsIgnoreCase(checkCode)) {
return false;
}
}
return true;
}
public boolean isValidate15Idcard(String idcard) {
if (idcard.length() != 15) {
return false;
}
if (isDigital(idcard)) {
String provinceid = idcard.substring(0, 2);
String birthday = idcard.substring(6, 12);
int year = Integer.parseInt(idcard.substring(6, 8));
int month = Integer.parseInt(idcard.substring(8, 10));
int day = Integer.parseInt(idcard.substring(10, 12));
boolean flag = false;
for (String id : cityCode) {
if (id.equals(provinceid)) {
flag = true;
break;
}
}
if (!flag) {
return false;
}
Date birthdate = null;
try {
birthdate = new SimpleDateFormat("yyMMdd").parse(birthday);
} catch (ParseException e) {
e.printStackTrace();
}
if (birthdate == null || new Date().before(birthdate)) {
return false;
}
GregorianCalendar curDay = new GregorianCalendar();
int curYear = curDay.get(Calendar.YEAR);
int year2bit = Integer.parseInt(String.valueOf(curYear)
.substring(2));
if ((year < 50 && year > year2bit)) {
return false;
}
if (month < 1 || month > 12) {
return false;
}
boolean mflag = false;
curDay.setTime(birthdate);
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
mflag = (day >= 1 && day <= 31);
break;
case 2:
if (curDay.isLeapYear(curDay.get(Calendar.YEAR))) {
mflag = (day >= 1 && day <= 29);
} else {
mflag = (day >= 1 && day <= 28);
}
break;
case 4:
case 6:
case 9:
case 11:
mflag = (day >= 1 && day <= 30);
break;
}
if (!mflag) {
return false;
}
} else {
return false;
}
return true;
}
public String convertIdcarBy15bit(String idcard) {
String idcard17 = null;
if (idcard.length() != 15) {
return null;
}
if (isDigital(idcard)) {
String birthday = idcard.substring(6, 12);
Date birthdate = null;
try {
birthdate = new SimpleDateFormat("yyMMdd").parse(birthday);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cday = Calendar.getInstance();
cday.setTime(birthdate);
String year = String.valueOf(cday.get(Calendar.YEAR));
idcard17 = idcard.substring(0, 6) + year + idcard.substring(8);
char c[] = idcard17.toCharArray();
String checkCode = "";
if (null != c) {
int bit[] = new int[idcard17.length()];
bit = converCharToInt(c);
int sum17 = 0;
sum17 = getPowerSum(bit);
checkCode = getCheckCodeBySum(sum17);
if (null == checkCode) {
return null;
}
idcard17 += checkCode;
}
} else {
return null;
}
return idcard17;
}
public boolean isIdcard(String idcard) {
return idcard == null || "".equals(idcard) ? false : Pattern.matches(
"(^\\d{15}$)|(\\d{17}(?:\\d|x|X)$)", idcard);
}
public boolean is15Idcard(String idcard) {
return idcard == null || "".equals(idcard) ? false : Pattern.matches(
"^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$",
idcard);
}
public boolean is18Idcard(String idcard) {
return Pattern
.matches(
"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([\\d|x|X]{1})$",
idcard);
}
public boolean isDigital(String str) {
return str == null || "".equals(str) ? false : str.matches("^[0-9]*$");
}
public int getPowerSum(int[] bit) {
int sum = 0;
if (power.length != bit.length) {
return sum;
}
for (int i = 0; i < bit.length; i++) {
for (int j = 0; j < power.length; j++) {
if (i == j) {
sum = sum + bit[i] * power[j];
}
}
}
return sum;
}
public String getCheckCodeBySum(int sum17) {
String checkCode = null;
switch (sum17 % 11) {
case 10:
checkCode = "2";
break;
case 9:
checkCode = "3";
break;
case 8:
checkCode = "4";
break;
case 7:
checkCode = "5";
break;
case 6:
checkCode = "6";
break;
case 5:
checkCode = "7";
break;
case 4:
checkCode = "8";
break;
case 3:
checkCode = "9";
break;
case 2:
checkCode = "x";
break;
case 1:
checkCode = "0";
break;
case 0:
checkCode = "1";
break;
}
return checkCode;
}
public int[] converCharToInt(char[] c) throws NumberFormatException {
int[] a = new int[c.length];
int k = 0;
for (char temp : c) {
a[k++] = Integer.parseInt(String.valueOf(temp));
}
return a;
}
public static void main(String[] args) throws Exception {
String idcard15 = "3312220802949";
String idcard18 = "330209200709163328";
IdcardValidatorUtils iv = new IdcardValidatorUtils();
boolean flag = false;
flag = iv.isValidate18Idcard(idcard18);
System.out.println("18位身份证号校验" + flag);
flag = iv.isValidate15Idcard(idcard15);
System.out.println("15位身份证号校验" + flag);
System.out.println("15位转18位身份证号" + iv.convertIdcarBy15bit(idcard15));
flag = iv.isValidate18Idcard(iv.convertIdcarBy15bit(idcard15));
System.out.println("15位转18位身份证号校验" + flag);
System.out.println(" 验证所有的身份证的合法性" + iv.isValidatedAllIdcard(idcard));
}
}
7. 大陆和香港号码格式验证
package com.hx.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class PhoneFormatCheckUtils {
public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
}
public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
String regExp = "^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
String regExp = "^(5|6|8|9)\\d{7}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
}