一些工具类
1、字符串处理工具类
1.1、StrUtils
package com.study.java8.util;/*** @Classname:StrUtils* @Description:字符串工具类* @Date:2023/9/9 9:37* @Author:jsz15*/import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.lang3.StringUtils;import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class StrUtils extends StringUtils {/*** 空字符串*/private static final String NULLSTR = "";/*** 下划线*/private static final char SEPARATOR = '_';/*** 获取参数不为空值** @param value defaultValue 要判断的value* @return value 返回值*/public static <T> T nvl(T value, T defaultValue) {return value != null ? value : defaultValue;}/*** * 判断一个Collection是否为空, 包含List,Set,Queue** @param coll 要判断的Collection* @return true:为空 false:非空*/public static boolean isEmpty(Collection<?> coll) {return isNull(coll) || coll.isEmpty();}/*** * 判断一个Collection是否非空,包含List,Set,Queue** @param coll 要判断的Collection* @return true:非空 false:空*/public static boolean isNotEmpty(Collection<?> coll) {return !isEmpty(coll);}/*** * 判断一个对象数组是否为空** @param objects 要判断的对象数组* * @return true:为空 false:非空*/public static boolean isEmpty(Object[] objects) {return isNull(objects) || (objects.length == 0);}/*** * 判断一个对象数组是否非空** @param objects 要判断的对象数组* @return true:非空 false:空*/public static boolean isNotEmpty(Object[] objects) {return !isEmpty(objects);}/*** * 判断一个Map是否为空** @param map 要判断的Map* @return true:为空 false:非空*/public static boolean isEmpty(Map<?, ?> map) {return isNull(map) || map.isEmpty();}/*** * 判断一个Map是否为空** @param map 要判断的Map* @return true:非空 false:空*/public static boolean isNotEmpty(Map<?, ?> map) {return !isEmpty(map);}/*** * 判断一个字符串是否为空串** @param str String* @return true:为空 false:非空*/public static boolean isEmpty(String str) {return isNull(str) || NULLSTR.equals(str.trim());}/*** * 判断一个字符串是否为非空串** @param str String* @return true:非空串 false:空串*/public static boolean isNotEmpty(String str) {return !isEmpty(str);}/*** * 判断一个对象是否为空** @param object Object* @return true:为空 false:非空*/public static boolean isNull(Object object) {return object == null;}/*** * 判断一个对象是否非空** @param object Object* @return true:非空 false:空*/public static boolean isNotNull(Object object) {return !isNull(object);}/*** * 判断一个对象是否是数组类型(Java基本型别的数组)** @param object 对象* @return true:是数组 false:不是数组*/public static boolean isArray(Object object) {return isNotNull(object) && object.getClass().isArray();}/*** 去空格*/public static String trim(String str) {return (str == null ? "" : str.trim());}/*** 截取字符串** @param str 字符串* @param start 开始* @return 结果*/public static String substring(final String str, int start) {if (str == null) {return NULLSTR;}if (start < 0) {start = str.length() + start;}if (start < 0) {start = 0;}if (start > str.length()) {return NULLSTR;}return str.substring(start);}/*** 截取字符串** @param str 字符串* @param start 开始* @param end 结束* @return 结果*/public static String substring(final String str, int start, int end) {if (str == null) {return NULLSTR;}if (end < 0) {end = str.length() + end;}if (start < 0) {start = str.length() + start;}if (end > str.length()) {end = str.length();}if (start > end) {return NULLSTR;}if (start < 0) {start = 0;}if (end < 0) {end = 0;}return str.substring(start, end);}/*** 格式化文本, {} 表示占位符<br>* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>* 例:<br>* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>** @param template 文本模板,被替换的部分用 {} 表示* @param params 参数值* @return 格式化后的文本*/public static String format(String template, Object... params) {if (isEmpty(params) || isEmpty(template)) {return template;}return StrFormatter.format(template, params);}/*** 驼峰首字符小写*/public static String uncapitalize(String str) {int strLen;if (str == null || (strLen = str.length()) == 0) {return str;}return new StrBuilder(strLen).append(Character.toLowerCase(str.charAt(0))).append(str.substring(1)).toString();}/*** 下划线转驼峰命名*/public static String toUnderScoreCase(String s) {if (s == null) {return null;}StringBuilder sb = new StringBuilder();boolean upperCase = false;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);boolean nextUpperCase = true;if (i < (s.length() - 1)) {nextUpperCase = Character.isUpperCase(s.charAt(i + 1));}if ((i > 0) && Character.isUpperCase(c)) {if (!upperCase || !nextUpperCase) {sb.append(SEPARATOR);}upperCase = true;} else {upperCase = false;}sb.append(Character.toLowerCase(c));}return sb.toString();}/*** 是否包含字符串** @param str 验证字符串* @param strs 字符串组* @return 包含返回true*/public static boolean inStringIgnoreCase(String str, String... strs) {if (str != null && strs != null) {for (String s : strs) {if (str.equalsIgnoreCase(trim(s))) {return true;}}}return false;}/*** 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld** @param name 转换前的下划线大写方式命名的字符串* @return 转换后的驼峰式命名的字符串*/public static String convertToCamelCase(String name) {StringBuilder result = new StringBuilder();// 快速检查if (name == null || name.isEmpty()) {// 没必要转换return "";} else if (!name.contains("_")) {// 不含下划线,仅将首字母大写return name.substring(0, 1).toUpperCase() + name.substring(1);}// 用下划线将原始字符串分割String[] camels = name.split("_");for (String camel : camels) {// 跳过原始字符串中开头、结尾的下换线或双重下划线if (camel.isEmpty()) {continue;}// 首字母大写result.append(camel.substring(0, 1).toUpperCase());result.append(camel.substring(1).toLowerCase());}return result.toString();}/*** 根据原始信息占位符中的内容进行变量提取 例如:a${b}c${d} -> [b,d]** @param content 原始信息* @param regex 占位符 例如:\\$\\{(.*?)\\}* @return*/public static List<String> extractToVar(String content, String regex) {Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(content);List<String> varList = new ArrayList<>();while (matcher.find()) {varList.add(matcher.group(1));}return varList;}/*** 根据原始信息占位符中的内容作为key,进行占位符替换** @param content 原始信息* @param regex 占位符正则 例如:\\$\\{(.*?)\\}* @param startStr 占位符开始* @param endStr 占位符结束* @param map 获取替换进占位符中的内容* @return*/public static String convertVar(String content, String regex, String startStr, String endStr, Map<String, String> map) {List<String> varList = extractToVar(content, regex);if (varList.size() > 0) {for (String s : varList) {if (map.containsKey(s) && null != map.get(s)) {content = content.replace(startStr + s + endStr, map.get(s));}}}return content;}/*** 根据原始信息占位符中的内容作为key,进行占位符替换** @param content 原始信息* @param varList 变量列表* @param startStr 占位符开始* @param endStr 占位符结束* @param map 获取替换进占位符中的内容* @return*/public static String convertToVar(String content, List<String> varList, String startStr, String endStr, Map<String, String> map) {if (varList.size() > 0) {for (String s : varList) {if (map.containsKey(s) && null != map.get(s)) {content = content.replace(startStr + s + endStr, map.get(s));}}}return content;}
}
1.2、StrFormatter
package com.study.java8.util;/*** @Classname:StrFormatter* @Description:TODO* @Date:2023/9/9 9:40* @Author:jsz15*/
public class StrFormatter {public static final String EMPTY_JSON = "{}";public static final char C_BACKSLASH = '\\';public static final char C_DELIM_START = '{';public static final char C_DELIM_END = '}';/*** 格式化字符串<br>* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>* 例:<br>* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>** @param strPattern 字符串模板* @param argArray 参数列表* @return 结果*/public static String format(final String strPattern, final Object... argArray) {if (StrUtils.isEmpty(strPattern) || StrUtils.isEmpty(argArray)) {return strPattern;}final int strPatternLength = strPattern.length();// 初始化定义好的长度以获得更好的性能StringBuilder sbuf = new StringBuilder(strPatternLength + 50);int handledPosition = 0;int delimIndex;// 占位符所在位置for (int argIndex = 0; argIndex < argArray.length; argIndex++) {delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);if (delimIndex == -1) {if (handledPosition == 0) {return strPattern;} else { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果sbuf.append(strPattern, handledPosition, strPatternLength);return sbuf.toString();}} else {if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) {if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) {// 转义符之前还有一个转义符,占位符依旧有效sbuf.append(strPattern, handledPosition, delimIndex - 1);sbuf.append(Convert.utf8Str(argArray[argIndex]));handledPosition = delimIndex + 2;} else {// 占位符被转义argIndex--;sbuf.append(strPattern, handledPosition, delimIndex - 1);sbuf.append(C_DELIM_START);handledPosition = delimIndex + 1;}} else {// 正常占位符sbuf.append(strPattern, handledPosition, delimIndex);sbuf.append(Convert.utf8Str(argArray[argIndex]));handledPosition = delimIndex + 2;}}}// append the characters following the last {} pair.// 加入最后一个占位符后所有的字符sbuf.append(strPattern, handledPosition, strPattern.length());return sbuf.toString();}}
1.3、Convert
package com.study.java8.util;import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Set;/*** @Description: 类型转换器* @Author: jsz* @date: 2023/9/9 11:12*/
public class Convert {/*** 转换为字符串<br>* 如果给定的值为null,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static String toStr(Object value, String defaultValue) {if (null == value) {return defaultValue;}if (value instanceof String) {return (String) value;}return value.toString();}/*** 转换为字符串<br>* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static String toStr(Object value) {return toStr(value, null);}/*** 转换为字符<br>* 如果给定的值为null,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Character toChar(Object value, Character defaultValue) {if (null == value) {return defaultValue;}if (value instanceof Character) {return (Character) value;}final String valueStr = toStr(value, null);return StrUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0);}/*** 转换为字符<br>* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Character toChar(Object value) {return toChar(value, null);}/*** 转换为byte<br>* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Byte toByte(Object value, Byte defaultValue) {if (value == null) {return defaultValue;}if (value instanceof Byte) {return (Byte) value;}if (value instanceof Number) {return ((Number) value).byteValue();}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {return Byte.parseByte(valueStr);} catch (Exception e) {return defaultValue;}}/*** 转换为byte<br>* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Byte toByte(Object value) {return toByte(value, null);}/*** 转换为Short<br>* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Short toShort(Object value, Short defaultValue) {if (value == null) {return defaultValue;}if (value instanceof Short) {return (Short) value;}if (value instanceof Number) {return ((Number) value).shortValue();}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {return Short.parseShort(valueStr.trim());} catch (Exception e) {return defaultValue;}}/*** 转换为Short<br>* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Short toShort(Object value) {return toShort(value, null);}/*** 转换为Number<br>* 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Number toNumber(Object value, Number defaultValue) {if (value == null) {return defaultValue;}if (value instanceof Number) {return (Number) value;}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {return NumberFormat.getInstance().parse(valueStr);} catch (Exception e) {return defaultValue;}}/*** 转换为Number<br>* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Number toNumber(Object value) {return toNumber(value, null);}/*** 转换为int<br>* 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Integer toInt(Object value, Integer defaultValue) {if (value == null) {return defaultValue;}if (value instanceof Integer) {return (Integer) value;}if (value instanceof Number) {return ((Number) value).intValue();}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {return Integer.parseInt(valueStr.trim());} catch (Exception e) {return defaultValue;}}/*** 转换为int<br>* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Integer toInt(Object value) {return toInt(value, null);}/*** 转换为Integer数组<br>** @param str 被转换的值* @return 结果*/public static Integer[] toIntArray(String str) {return toIntArray(",", str);}/*** 转换为List<String>数组<br>** @param str 被转换的值* @return 结果*/public static List<String> toListStrArray(String str) {String[] stringArray = toStrArray(str);List<String> stringB = Arrays.asList(stringArray);return stringB;}/*** 转换为Long数组<br>** @param str 被转换的值* @return 结果*/public static Long[] toLongArray(String str) {return toLongArray(",", str);}/*** 转换为Integer数组<br>** @param split 分隔符* @param split 被转换的值* @return 结果*/public static Integer[] toIntArray(String split, String str) {if (StrUtils.isEmpty(str)) {return new Integer[]{};}String[] arr = str.split(split);final Integer[] ints = new Integer[arr.length];for (int i = 0; i < arr.length; i++) {final Integer v = toInt(arr[i], 0);ints[i] = v;}return ints;}/*** 转换为Long数组<br>** @param split 是否忽略转换错误,忽略则给值null* @param str 被转换的值* @return 结果*/public static Long[] toLongArray(String split, String str) {if (StrUtils.isEmpty(str)) {return new Long[]{};}String[] arr = str.split(split);final Long[] longs = new Long[arr.length];for (int i = 0; i < arr.length; i++) {final Long v = toLong(arr[i], null);longs[i] = v;}return longs;}/*** 转换为String数组<br>** @param str 被转换的值* @return 结果*/public static String[] toStrArray(String str) {return toStrArray(",", str);}/*** 转换为String数组<br>** @param split 分隔符* @param split 被转换的值* @return 结果*/public static String[] toStrArray(String split, String str) {return str.split(split);}/*** 转换为long<br>* 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Long toLong(Object value, Long defaultValue) {if (value == null) {return defaultValue;}if (value instanceof Long) {return (Long) value;}if (value instanceof Number) {return ((Number) value).longValue();}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {// 支持科学计数法return new BigDecimal(valueStr.trim()).longValue();} catch (Exception e) {return defaultValue;}}/*** 转换为long<br>* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Long toLong(Object value) {return toLong(value, null);}/*** 转换为double<br>* 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Double toDouble(Object value, Double defaultValue) {if (value == null) {return defaultValue;}if (value instanceof Double) {return (Double) value;}if (value instanceof Number) {return ((Number) value).doubleValue();}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {// 支持科学计数法return new BigDecimal(valueStr.trim()).doubleValue();} catch (Exception e) {return defaultValue;}}/*** 转换为double<br>* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Double toDouble(Object value) {return toDouble(value, null);}/*** 转换为Float<br>* 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Float toFloat(Object value, Float defaultValue) {if (value == null) {return defaultValue;}if (value instanceof Float) {return (Float) value;}if (value instanceof Number) {return ((Number) value).floatValue();}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {return Float.parseFloat(valueStr.trim());} catch (Exception e) {return defaultValue;}}/*** 转换为Float<br>* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Float toFloat(Object value) {return toFloat(value, null);}/*** 转换为boolean<br>* String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static Boolean toBool(Object value, Boolean defaultValue) {if (value == null) {return defaultValue;}if (value instanceof Boolean) {return (Boolean) value;}String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}valueStr = valueStr.trim().toLowerCase();switch (valueStr) {case "true":return true;case "false":return false;case "yes":return true;case "ok":return true;case "no":return false;case "1":return true;case "0":return false;default:return defaultValue;}}/*** 转换为boolean<br>* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static Boolean toBool(Object value) {return toBool(value, null);}/*** 转换为Enum对象<br>* 如果给定的值为空,或者转换失败,返回默认值<br>** @param clazz Enum的Class* @param value 值* @param defaultValue 默认值* @return Enum*/public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value, E defaultValue) {if (value == null) {return defaultValue;}if (clazz.isAssignableFrom(value.getClass())) {@SuppressWarnings("unchecked")E myE = (E) value;return myE;}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {return Enum.valueOf(clazz, valueStr);} catch (Exception e) {return defaultValue;}}/*** 转换为Enum对象<br>* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>** @param clazz Enum的Class* @param value 值* @return Enum*/public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value) {return toEnum(clazz, value, null);}/*** 转换为BigInteger<br>* 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static BigInteger toBigInteger(Object value, BigInteger defaultValue) {if (value == null) {return defaultValue;}if (value instanceof BigInteger) {return (BigInteger) value;}if (value instanceof Long) {return BigInteger.valueOf((Long) value);}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {return new BigInteger(valueStr);} catch (Exception e) {return defaultValue;}}/*** 转换为BigInteger<br>* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static BigInteger toBigInteger(Object value) {return toBigInteger(value, null);}/*** 转换为BigDecimal<br>* 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @param defaultValue 转换错误时的默认值* @return 结果*/public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) {if (value == null) {return defaultValue;}if (value instanceof BigDecimal) {return (BigDecimal) value;}if (value instanceof Long) {return new BigDecimal((Long) value);}if (value instanceof Double) {return new BigDecimal((Double) value);}if (value instanceof Integer) {return new BigDecimal((Integer) value);}final String valueStr = toStr(value, null);if (StrUtils.isEmpty(valueStr)) {return defaultValue;}try {return new BigDecimal(valueStr);} catch (Exception e) {return defaultValue;}}/*** 转换为BigDecimal<br>* 如果给定的值为空,或者转换失败,返回默认值<br>* 转换失败不会报错** @param value 被转换的值* @return 结果*/public static BigDecimal toBigDecimal(Object value) {return toBigDecimal(value, null);}/*** 将对象转为字符串<br>* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法** @param obj 对象* @return 字符串*/public static String utf8Str(Object obj) {return str(obj, CharsetKit.CHARSET_UTF_8);}/*** 将对象转为字符串<br>* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法** @param obj 对象* @param charsetName 字符集* @return 字符串*/public static String str(Object obj, String charsetName) {return str(obj, Charset.forName(charsetName));}/*** 将对象转为字符串<br>* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法** @param obj 对象* @param charset 字符集* @return 字符串*/public static String str(Object obj, Charset charset) {if (null == obj) {return null;}if (obj instanceof String) {return (String) obj;} else if (obj instanceof byte[] || obj instanceof Byte[]) {return str((Byte[]) obj, charset);} else if (obj instanceof ByteBuffer) {return str((ByteBuffer) obj, charset);}return obj.toString();}/*** 将byte数组转为字符串** @param bytes byte数组* @param charset 字符集* @return 字符串*/public static String str(byte[] bytes, String charset) {return str(bytes, StrUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset));}/*** 解码字节码** @param data 字符串* @param charset 字符集,如果此字段为空,则解码的结果取决于平台* @return 解码后的字符串*/public static String str(byte[] data, Charset charset) {if (data == null) {return null;}if (null == charset) {return new String(data);}return new String(data, charset);}/*** 将编码的byteBuffer数据转换为字符串** @param data 数据* @param charset 字符集,如果为空使用当前系统字符集* @return 字符串*/public static String str(ByteBuffer data, String charset) {if (data == null) {return null;}return str(data, Charset.forName(charset));}/*** 将编码的byteBuffer数据转换为字符串** @param data 数据* @param charset 字符集,如果为空使用当前系统字符集* @return 字符串*/public static String str(ByteBuffer data, Charset charset) {if (null == charset) {charset = Charset.defaultCharset();}return charset.decode(data).toString();}// ----------------------------------------------------------------------- 全角半角转换/*** 半角转全角** @param input String.* @return 全角字符串.*/public static String toSBC(String input) {return toSBC(input, null);}/*** 半角转全角** @param input String* @param notConvertSet 不替换的字符集合* @return 全角字符串.*/public static String toSBC(String input, Set<Character> notConvertSet) {char c[] = input.toCharArray();for (int i = 0; i < c.length; i++) {if (null != notConvertSet && notConvertSet.contains(c[i])) {// 跳过不替换的字符continue;}if (c[i] == ' ') {c[i] = '\u3000';} else if (c[i] < '\177') {c[i] = (char) (c[i] + 65248);}}return new String(c);}/*** 全角转半角** @param input String.* @return 半角字符串*/public static String toDBC(String input) {return toDBC(input, null);}/*** 替换全角为半角** @param text 文本* @param notConvertSet 不替换的字符集合* @return 替换后的字符*/public static String toDBC(String text, Set<Character> notConvertSet) {char c[] = text.toCharArray();for (int i = 0; i < c.length; i++) {if (null != notConvertSet && notConvertSet.contains(c[i])) {// 跳过不替换的字符continue;}if (c[i] == '\u3000') {c[i] = ' ';} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {c[i] = (char) (c[i] - 65248);}}String returnString = new String(c);return returnString;}/*** 数字金额大写转换 先写个完整的然后将如零拾替换成零** @param n 数字* @return 中文大写数字*/public static String digitUppercase(double n) {String[] fraction = {"角", "分"};String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};String[][] unit = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}};String head = n < 0 ? "负" : "";n = Math.abs(n);String s = "";for (int i = 0; i < fraction.length; i++) {s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");}if (s.length() < 1) {s = "整";}int integerPart = (int) Math.floor(n);for (int i = 0; i < unit[0].length && integerPart > 0; i++) {String p = "";for (int j = 0; j < unit[1].length && n > 0; j++) {p = digit[integerPart % 10] + unit[1][j] + p;integerPart = integerPart / 10;}s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;}return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$","零元整");}}
1.4、CharsetKit
package com.study.java8.util;import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;/*** @Description: 字符集工具类* @Author: jsz* @date: 2023/9/9 11:11*/
public class CharsetKit {/*** ISO-8859-1*/public static final String ISO_8859_1 = "ISO-8859-1";/*** UTF-8*/public static final String UTF_8 = "UTF-8";/*** GBK*/public static final String GBK = "GBK";/*** ISO-8859-1*/public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1);/*** UTF-8*/public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);/*** GBK*/public static final Charset CHARSET_GBK = Charset.forName(GBK);/*** 转换为Charset对象** @param charset 字符集,为空则返回默认字符集* @return Charset*/public static Charset charset(String charset) {return StrUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);}/*** 转换字符串的字符集编码** @param source 字符串* @param srcCharset 源字符集,默认ISO-8859-1* @param destCharset 目标字符集,默认UTF-8* @return 转换后的字符集*/public static String convert(String source, String srcCharset, String destCharset) {return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));}/*** 转换字符串的字符集编码** @param source 字符串* @param srcCharset 源字符集,默认ISO-8859-1* @param destCharset 目标字符集,默认UTF-8* @return 转换后的字符集*/public static String convert(String source, Charset srcCharset, Charset destCharset) {if (null == srcCharset) {srcCharset = StandardCharsets.ISO_8859_1;}if (null == destCharset) {srcCharset = StandardCharsets.UTF_8;}if (StrUtils.isEmpty(source) || srcCharset.equals(destCharset)) {return source;}return new String(source.getBytes(srcCharset), destCharset);}/*** @return 系统字符集编码*/public static String systemCharset() {return Charset.defaultCharset().name();}}
2、日期格式化处理工具类
2.1、ValidateUtils
package com.study.java8.util;import java.util.Calendar;
import java.util.Collection;
import java.util.regex.Pattern;/*** @Classname:ValidateUtils* @Description:字符串校验工具类* @Date:2023/9/9 9:37* @Author:jsz15*/
public class ValidateUtils {/*** 字符串缺省状态*/private static final boolean DEFAULT_EMPTY_OK = false;/*** 数字chars*/private static final String DIGITS = "0123456789";/*** 小写字母chars*/public static final String LETTERS_LOWERCASE = "abcdefghijklmnopqrstuvwxyz";/*** 小写字母chars + 数字*/public static final String LETTERS_LOWERCASE_DIGITS = LETTERS_LOWERCASE+ DIGITS;/*** 大写字母chars*/public static final String LETTERS_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";/*** 大写字母chars + 数字*/public static final String LETTERS_UPPERCASE_DIGITS = LETTERS_UPPERCASE + DIGITS;/*** 全部字母chars*/public static final String LETTERS = LETTERS_LOWERCASE + LETTERS_UPPERCASE;/*** 全部字母数字*/public static final String LETTERS_DIGITS = LETTERS + DIGITS;/*** 空白的chars (包括空格,\t,\n,\r)*/private static final String WHITE_SPACE = " \t\n\r";/*** 小数点*/private static final String DECIMAL_POING_DELIMITER = ".";/*** 电话号码里允许的不是数字的chars ,两边括号,横线,空格*/private static final String PHONE_NUMBER_DELIMITERS = "()- ";/*** 全球电话号码允许"+"号的chars*/private static final String VALID_PHONE_CHARS_WORLD = "+" + DIGITS + PHONE_NUMBER_DELIMITERS;/*** 手机号码允许"+"号和数字,但只允许第一个字符是+号,验证是检查是否第一个是,如果是去除再验证*/private static final String VALID_MSISDN_CHARS = DIGITS;/*** 手机号码允许的最大长度*/private static final int VALID_MSISDN_MAXLEN = 21;/*** 手机号码允许的最小长度*/private static final int VALID_MSISDN_MINLEN = 11;/*** 定义12月份对应的天数*/private static final int[] DAYS_IN_MONTH = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};/*** 检查两个对象是否相等*/public static boolean isEqual(Object obj, Object obj2) {return (obj == null) ? (obj2 == null) : obj.equals(obj2);}/*** 检查字符串是否为空*/public static boolean isEmpty(Object obj) {if (obj == null)return true;if (obj instanceof String)return isEmpty((String) obj);return false;}/*** 检查字符串是否为空*/public static boolean isEmpty(String s) {return ((s == null) || (s.trim().length() == 0));}/*** 检查集合是否为空*/public static boolean isEmpty(Collection<?> c) {return ((c == null) || (c.size() == 0));}/*** 检查字符串是否不为空*/public static boolean isNotEmpty(String s) {return ((s != null) && (s.trim().length() > 0));}/*** 检查集合是否不为空*/public static boolean isNotEmpty(Collection<?> c) {return ((c != null) && (c.size() > 0));}/*** 如果s中存在c,则返回true,否则返回false*/public static boolean isCharInString(char c, String s) {return (s.indexOf(c) != -1);}/*** 检查字符是否是大写字母,(注:A-Z之间)*/public static boolean isLetterUppercase(char c) {return LETTERS_UPPERCASE.indexOf(c) != -1;}/*** 检查字符是否是大写字母加数字,(注:A-Z,0-9之间)*/public static boolean isLetterUppercaseDigits(char c) {return LETTERS_UPPERCASE_DIGITS.indexOf(c) != -1;}/*** 检查字符是否是小写字母,(注:a-z之间)*/public static boolean isLetterLowercase(char c) {return LETTERS_LOWERCASE.indexOf(c) != -1;}/*** 检查字符是否是小写字母加数字,(注:a-z,0-9之间)*/public static boolean isLetterLowercaseDigits(char c) {return LETTERS_LOWERCASE_DIGITS.indexOf(c) != -1;}/*** 检查字符是否是字母,(注:a-z,A-Z之间)*/public static boolean isLetter(char c) {return LETTERS.indexOf(c) != -1;}/*** 检查字符是否是数字*/public static boolean isDigit(char c) {return DIGITS.indexOf(c) != -1;}/*** 检查字符是否是数字或字母*/public static boolean isLetterOrDigit(char c) {return LETTERS_DIGITS.indexOf(c) != -1;}/*** 1\如果字符串为空或全是whitespace中的值则返回true,存在一个不是则返回false 2\见whitespace定义* whitespace = " \t\n\r";(空格,\t,\n,\r)*/public static boolean isWhitespace(String s) {if (isEmpty(s))return true;// 逐个字符检查,如果发现一个不是whitespace,则返回falsefor (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (WHITE_SPACE.indexOf(c) == -1)return false;}return true;}/*** 检查是否是指定的长度,注:当s=null || s="",min=0时为true*/public static boolean isLen(String s, int min, int max) {if (isEmpty(s))return min == 0 ? true : false;return (s.length() >= min && s.length() <= max);}/*** 检查是否GBK编码长度,数据库一般是一个汉字两个字节*/public static boolean isByteLen(String s, int min, int max) {if (isEmpty(s))return min == 0 ? true : false;int len = 0;try {len = s.getBytes("GBK").length;} catch (Exception e) {len = s.getBytes().length;}return (len >= min && len <= max);}/*** 检查是否指定编码长度,UTF-8是一个汉字3个字节,GBK是两个*/public static boolean isByteLen(String s, int min, int max, String encoding) {if (isEmpty(s))return min == 0 ? true : false;int len = 0;try {len = s.getBytes(encoding).length;} catch (Exception e) {len = s.getBytes().length;}return (len >= min && len <= max);}/*** 检查是否是整型*/public static boolean isInteger(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;// 逐个检查,如果出现一个字符不是数字则返回falsefor (int i = 0; i < s.length(); i++) {if (!isDigit(s.charAt(i)))return false;}return true;}/*** 检查是否是带符号的整型(允许第一个字符为"+,-",不接受浮点".",指数"E"等*/public static boolean isSignedInteger(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;try {Integer.parseInt(s);return true;} catch (Exception e) {return false;}}/*** 检查是否是带符号的长整型(允许第一个字符为"+,-",不接受浮点".",指数"E"等*/public static boolean isSignedLong(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;try {Long.parseLong(s);return true;} catch (Exception e) {return false;}}/*** 检查是否是一个正整数*/public static boolean isPositiveInteger(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;try {long temp = Long.parseLong(s);if (temp > 0)return true;return false;} catch (Exception e) {return false;}}/*** 检查是否是一个非负整数*/public static boolean isNonnegativeInteger(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;try {int temp = Integer.parseInt(s);if (temp >= 0)return true;return false;} catch (Exception e) {return false;}}/*** 检查是否是一个负整数*/public static boolean isNegativeInteger(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;try {int temp = Integer.parseInt(s);if (temp < 0)return true;return false;} catch (Exception e) {return false;}}/*** 检查是否是一个非正整数*/public static boolean isNonpositiveInteger(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;try {int temp = Integer.parseInt(s);if (temp <= 0)return true;return false;} catch (Exception e) {return false;}}/*** 检查字符串是否是整型,且在a,b之间,>=a,<=b*/public static boolean isIntegerInRange(String s, int a, int b) {if (isEmpty(s))return DEFAULT_EMPTY_OK;if (!isSignedInteger(s))return false;int num = Integer.parseInt(s);return ((num >= a) && (num <= b));}/*** 检查字符串是否是正整型,且在a,b之间,>=a,<=b*/public static boolean isIntegerInRangeLen(String s, int a, int b) {if (isEmpty(s))return DEFAULT_EMPTY_OK;if (!isInteger(s))return false;return ((s.length() >= a) && (s.length() <= b));}/*** 是否是Unicode码*/public static final boolean isUnicode(String str) {if (isEmpty(str))return false;int len = str.length();for (int i = 0; i < len; i++) {if ((int) str.charAt(i) > 128)return true;}if (str.length() == 1) {if (((int) str.charAt(0)) > 128)return true;}return false;}/*** 检查是否是一个无符号的浮点型,不支持指点E*/public static boolean isFloat(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;if (s.startsWith(DECIMAL_POING_DELIMITER))return false;// 只允许一个点.boolean seenDecimalPoint = false;// 逐个字符检查for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (isDigit(c))continue;if (c == DECIMAL_POING_DELIMITER.charAt(0)) {if (!seenDecimalPoint) {seenDecimalPoint = true;continue;}}return false;}return true;}/*** 检查是否是一个允许符号的浮点型,允许符号"+","-"*/public static boolean isSignedFloat(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;try {float temp = Float.parseFloat(s);if (temp <= 0)return true;return false;} catch (Exception e) {return false;}}/*** 检查是否是一个允许符号的双精度浮点型,允许符号"+","-"*/public static boolean isSignedDouble(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;try {Double.parseDouble(s);return true;} catch (Exception e) {return false;}}/*** 检查字符串是否都是由字母组成*/public static boolean isAlphabetic(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!isLetter(c))return false;}return true;}/*** 检查字符串是否都是由小写字母组成*/public static boolean isAlphabeticLowercase(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!isLetterLowercase(c))return false;}return true;}/*** 检查字符串是否都是由大写字母组成*/public static boolean isAlphabeticUppercase(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!isLetterUppercase(c))return false;}return true;}/*** 检查字符串是否都是由字母组成且长度在min,max范围内*/public static boolean isAlphabeticLen(String s, int min, int max) {if (isEmpty(s))return min == 0 ? true : false;if (!isAlphabetic(s))return false;if (s.length() < min || s.length() > max)return false;return true;}/*** 检查字符串是否都是由小写字母组成且长度在min,max范围内*/public static boolean isAlphabeticLowercaseLen(String s, int min, int max) {if (isEmpty(s))return min == 0 ? true : false;if (!isAlphabeticLowercase(s))return false;if (s.length() < min || s.length() > max)return false;return true;}/*** 检查字符串是否都是由大字母组成且长度在min,max范围内*/public static boolean isAlphabeticUpperLen(String s, int min, int max) {if (isEmpty(s))return min == 0 ? true : false;if (!isAlphabeticUppercase(s))return false;if (s.length() < min || s.length() > max)return false;return true;}/*** 检查字符串是否都是由字母或数字组成*/public static boolean isAlphanumeric(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!isLetterOrDigit(c))return false;}return true;}/*** 检查字符串是否都是由字母或数字组成且长度在min,max范围内*/public static boolean isAlphanumericLen(String s, int min, int max) {if (isEmpty(s))return min == 0 ? true : false;if (!isAlphanumeric(s))return false;if (s.length() < min || s.length() > max)return false;return true;}/*** 检查字符串是否都是由大写字母或数字组成*/public static boolean isAlphaUpperNumeric(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!isLetterUppercaseDigits(c))return false;}return true;}/*** 检查字符串是否都是由大写字母或数字组成*/public static boolean isAlphaLowerNumeric(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!isLetterLowercaseDigits(c))return false;}return true;}/*** 检查字符串是否都是由大写字母或数字组成*/public static boolean isAlphaUpperNumericLen(String s, int min, int max) {if (isEmpty(s))return min == 0 ? true : false;if (!isAlphaUpperNumeric(s))return false;if (s.length() < min || s.length() > max)return false;return true;}/*** 检查字符串是否都是由小写字母或数字组成*/public static boolean isAlphaLowerNumericLen(String s, int min, int max) {if (isEmpty(s))return min == 0 ? true : false;if (!isAlphaLowerNumeric(s))return false;if (s.length() < min || s.length() > max)return false;return true;}/*** 检查字符串是否正确的邮政编码*/public static boolean isZipCode(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;if (s.length() != 6 || !isInteger(s))return false;return true;}public static boolean isMoneyTwoRadix(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;// 去除负号if (s.startsWith("-"))s = s.substring(1);int ind = s.indexOf(".");if (ind == -1)return isInteger(s);// 如果没有点号,则判断是否是整数if (ind == 0)return false;String integer = s.substring(0, ind);String radix = s.substring(ind + 1);if (!isInteger(integer) || !isIntegerInRangeLen(radix, 2, 2))return false;// 如果整数部分不是整数,小数部分不是整数,或小数部分不是两位return true;}/*** 检查字符串是否正确的邮件地址(注:要求存在@字符,且不是出现在第一个,最后一个位置,现在不检查是否存在".")*/public static boolean isEmail(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;if (isWhitespace(s))return false;int indexLeft = s.indexOf('@');int indexRight = s.lastIndexOf('@');// 如果不存在@,或不止一个,或第一个,或最后一个if (indexLeft < 1 || indexLeft != indexRight || indexLeft == s.length())return false;return true;}/*** 检查是否是正确的年*/public static boolean isYear(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;if (!isNonnegativeInteger(s))return false;return ((s.length() == 2) || (s.length() == 4));}/*** 判断是否是周末 yyyy-MM-dd*/public static boolean isWeekend(String date) {Calendar calendar = DateTimeUtils.toCalendar(date + " 00:00:01");return calendar.get(Calendar.DAY_OF_WEEK) == 1;}/*** 判断是否季度末 yyyy-MM-dd*/public static boolean isMonthQuarter(String date) {if (!isDate(date))return false;String year = date.substring(0, 4);String month = date.substring(5, 7);String day = date.substring(8);if (!isMonthLastDay(year, month, day))return false;if (month.equals("03") || month.equals("06") || month.equals("09")|| month.equals("12"))return true;return false;}/*** 判断是否年末 yyyy-MM-dd*/public static boolean isYearLastDay(String date) {if (!isDate(date))return false;String year = date.substring(0, 4);String month = date.substring(5, 7);String day = date.substring(8);if (!isMonthLastDay(year, month, day))return false;if (month.equals("12"))return true;return false;}/*** 检查是否是正确的月*/public static boolean isMonth(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;return isIntegerInRange(s, 1, 12);}/*** 检查是否是正确的日*/public static boolean isDay(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;return isIntegerInRange(s, 1, 31);}/*** 检查是否闰年*/public static boolean isLeapYear(int year) {return (year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0));}/*** 检查是否是月末 yyyy-MM-dd HH:mm:ss*/public static boolean isMonthLastDay(String date) {if (!isDate(date))return false;String year = date.substring(0, 4);String month = date.substring(5, 7);String day = date.substring(8);return isMonthLastDay(year, month, day);}/*** 检查是否是月末*/public static boolean isMonthLastDay(String year, String month, String day) {if (!isDate(year, month, day))return false;int yearInt = Integer.parseInt(year);int monthInt = Integer.parseInt(month);int dayInt = Integer.parseInt(day);return isMonthLastDay(yearInt, monthInt, dayInt);}/*** 检查是否是月末*/public static boolean isMonthLastDay(int year, int month, int day) {if (year < 1000 || year > 9999 || month > 12 || month < 1 || day > 31|| day < 1)return false;switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:return day == 31;case 4:case 6:case 9:case 11:return day == 30;default:// 2月boolean isLeapYear = ValidateUtils.isLeapYear(year);return isLeapYear ? day == 29 : day == 28;}}/*** 检查是否是正确的时*/public static boolean isHour(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;return isIntegerInRange(s, 0, 23);}/*** 检查是否是正确的分*/public static boolean isMinute(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;return isIntegerInRange(s, 0, 59);}/*** 检查是否是正确的秒*/public static boolean isSecond(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;return isIntegerInRange(s, 0, 59);}/*** 检查是否是正确的日期*/public static boolean isDate(String year, String month, String day) {if (!(isYear(year) && isMonth(month) && isDay(day)))return false;int intYear = Integer.parseInt(year);int intMonth = Integer.parseInt(month);int intDay = Integer.parseInt(day);if (intDay > DAYS_IN_MONTH[intMonth - 1])return false;if ((intMonth == 2) && (intDay > (isLeapYear(intYear) ? 29 : 28)))return false;return true;}/*** 检查是否是正确的日期*/public static boolean isDate(String date) {if (isEmpty(date))return DEFAULT_EMPTY_OK;if (date.length() != 10)return DEFAULT_EMPTY_OK;int dateSlash1 = date.indexOf("-");int dateSlash2 = date.lastIndexOf("-");if (dateSlash1 <= 0 || dateSlash1 == dateSlash2)return false;String year = date.substring(0, dateSlash1);String month = date.substring(dateSlash1 + 1, dateSlash2);String day = date.substring(dateSlash2 + 1);return isDate(year, month, day);}/*** 判断是不是指定的时间格式*/public static boolean isDateTime(String datetime) {if (isEmpty(datetime))return false;datetime = datetime.trim();String[] strs = datetime.split(" ");if (strs.length != 2)return false;return isDate(strs[0]) && isTime(strs[1]);}/*** 判断是不是指定的时间格式, spe为日期分隔符*/public static boolean isDateTime(String datetime, String spe) {if (isEmpty(datetime))return false;datetime = datetime.trim();String[] strs = datetime.split(" ");if (strs.length != 2)return false;return isDate(strs[0].replaceAll(spe, "-")) && isTime(strs[1]);}/*** 检查是否是西方正确的日期*/public static boolean isEnglishDate(String date) {if (isEmpty(date))return DEFAULT_EMPTY_OK;int dateSlash1 = date.indexOf("/");int dateSlash2 = date.lastIndexOf("/");if (dateSlash1 <= 0 || dateSlash1 == dateSlash2)return false;String month = date.substring(0, dateSlash1);String day = date.substring(dateSlash1 + 1, dateSlash2);String year = date.substring(dateSlash2 + 1);return isDate(year, month, day);}/*** 检查是否是日期比今天大*/public static boolean isDateAfterToday(String date) {if (isDate(date))return DEFAULT_EMPTY_OK;java.util.Date passed = DateTimeUtils.toDate(date, "00:00:00");java.util.Date now = DateTimeUtils.nowDate();return passed.after(now);}/*** 检查是否是正确的时间*/public static boolean isTime(String hour, String minute, String second) {if (isHour(hour) && isMinute(minute) && isSecond(second))return true;return false;}/*** 检查是否是正确的时间*/public static boolean isTime(String time) {if (isEmpty(time))return DEFAULT_EMPTY_OK;int timeColon1 = time.indexOf(":");int timeColon2 = time.lastIndexOf(":");if (timeColon1 <= 0 || timeColon1 == timeColon2)return false;String hour = time.substring(0, timeColon1);String minute = time.substring(timeColon1 + 1, timeColon2);String second = time.substring(timeColon2 + 1);return isTime(hour, minute, second);}/*** 检查是否是正确的电话号码*/public static boolean isPhone(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;// 逐个字符检查,如果发现一个不是whitespace,则返回falsefor (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!isCharInString(c, VALID_PHONE_CHARS_WORLD))return false;}return true;}/*** 检查是否是正确的手机号码*/public static boolean isMsisdn(String s) {if (isEmpty(s))return DEFAULT_EMPTY_OK;// 如果第一个是+号,则去除if (s.charAt(0) == '+')s = s.substring(1);if (s.length() > VALID_MSISDN_MAXLEN|| s.length() < VALID_MSISDN_MINLEN)return false;// 逐个字符检查,如果发现一个不是VALID_MSISDN_CHARS,则返回falsefor (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!isCharInString(c, VALID_MSISDN_CHARS))return false;}return true;}/*** 判断号码是否符合配置文件所设条件** @param phone 号码字符串* @return boolean =true 是手机号码,=false 非手机号码* @oaram prefixs 固定前三个的前缀,如135,136,159等,多个用逗号隔开*/public static boolean isMsisdn11(String phone, String prefixs) {if (!isIntegerInRangeLen(phone, 11, 11))return false;String[] prefixArr = prefixs.split(",");for (int i = 0; i < prefixArr.length; i++) {if (phone.startsWith(prefixArr[i]))return true;}return false;}/*** 判断号码是否符合配置文件所设条件** @param phone 号码字符串* @param prefixs 前缀数组,如135,137,+86,0086,17951135等,多个用逗号隔开* @return boolean =true 是手机号码,=false 非手机号码*/public static boolean isMsisdn21(String phone, String prefixs) {if (!isMsisdn(phone))return false;String[] prefixArr = prefixs.split(",");for (int i = 0; i < prefixArr.length; i++) {if (phone.length() != prefixArr[i].length() + 8)continue;if (phone.startsWith(prefixArr[i]))return true;}return false;}/*** 检查是否是IP地址,ip为空返回false;*/public static boolean isIP(String ip) {return isIP(ip, false);}/*** 检查是否是IP地址*/public static boolean isIP(String ip, boolean allowEmpty) {if (isEmpty(ip))return allowEmpty;try {int ind1 = ip.indexOf('.');if (ind1 == -1)return false;String str1 = ip.substring(0, ind1);if (!ValidateUtils.isIntegerInRange(str1, 0, 255))return false;int ind2 = ip.indexOf('.', ind1 + 1);if (ind2 == -1)return false;String str2 = ip.substring(ind1 + 1, ind2);if (!ValidateUtils.isIntegerInRange(str2, 0, 255))return false;int ind3 = ip.indexOf('.', ind2 + 1);if (ind3 == -1)return false;String str3 = ip.substring(ind2 + 1, ind3);if (!ValidateUtils.isIntegerInRange(str3, 0, 255))return false;String str4 = ip.substring(ind3 + 1);if (!ValidateUtils.isIntegerInRange(str4, 0, 255))return false;} catch (Exception e) {return false;}return true;}/*** 检查是否是macAddress,macAddress为空返回false;*/public static boolean isMacAddress(String macAddress) {return isMacAddress(macAddress, false);}/*** 检查是否是IP地址*/public static boolean isMacAddress(String macAddress, boolean allowEmpty) {if (isEmpty(macAddress))return allowEmpty;return isRegExp(macAddress,"^[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}$");}/*** 检查是否邮编*/public static boolean isPostalCode(String s) {if (!isInteger(s) || s.trim().length() != 6)return false;return true;}/*** 检查是否在指定的字符串内*/public static boolean isScope(String s, String scope) {if (ValidateUtils.isEmpty(s))return ValidateUtils.DEFAULT_EMPTY_OK;// 逐个字符检查,如果发现一个不是specifyStr,则返回falsefor (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (!ValidateUtils.isCharInString(c, scope))return false;}return true;}/*** 检查value是否符合指定的pattern*/public static boolean isRegExp(String value, String regExp) {if (regExp.startsWith("/"))regExp = regExp.substring(1);if (regExp.endsWith("/"))regExp = regExp.substring(0, regExp.length() - 1);return Pattern.matches(regExp, value);}/*** 检查src是否包含字符串数组任何一个*/public static boolean isStrContainStrArr(String src, String[] strs) {for (String str : strs) {if (src.contains(str.trim()))return true;}return false;}/*** 检查src是否包含字符串数组任何一个*/public static boolean isStrContainStrArr(String src, String strArr,String delm) {return isStrContainStrArr(src, strArr.split(delm));}
}
2.2、DateTimeUtils
package com.study.java8.util;import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;/*** @Description: 时间处理工具类* @Author: jsz* @date: 2023/9/9 11:13*/
public class DateTimeUtils {public static final SimpleDateFormat FORMAT_YYYY_MM_DDHHMMSSSSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");public static final SimpleDateFormat FORMAT_YYYY_MM_DDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static final SimpleDateFormat FORMAT_YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd");public static final SimpleDateFormat FORMAT_YYYY_MM = new SimpleDateFormat("yyyy-MM");public static final SimpleDateFormat FORMAT_YYYYMMDDHHMMSS17 = new SimpleDateFormat("yyyyMMddHHmmssSSS");public static final SimpleDateFormat FORMAT_YYYYMMDDHHMMSS14 = new SimpleDateFormat("yyyyMMddHHmmss");public static final SimpleDateFormat FORMAT_YYMMDDHHMMSS12 = new SimpleDateFormat("yyMMddHHmmss");public static final SimpleDateFormat FORMAT_YYYYMMDD8 = new SimpleDateFormat("yyyyMMdd");public static final SimpleDateFormat FORMAT_YYYYMM6 = new SimpleDateFormat("yyyyMM");public static final SimpleDateFormat FORMAT_HHMMSS8 = new SimpleDateFormat("HH:mm:ss");/*** 返回当前时间的Date*/public static Date nowDate() {return new Date();}/*** 字符串转为时间,字符串符合标准格式:"YYYY-MM-DD HH:MM:SS"** @param dateTime 标准时间格式 "YYYY-MM-DD HH:MM:SS"* @return java.util.Date*/public static Date toDate(String dateTime) {if (dateTime.length() > "YYYY-MM-DD HH:MM:SS".length())dateTime = dateTime.substring(0, "YYYY-MM-DD HH:MM:SS".length());int index = dateTime.indexOf(" ");String date = dateTime.substring(0, index);String time = dateTime.substring(index + 1);return toDate(date, time);}/*** 字符串转为时间,字符串符合标准日期格式:"YYYY-MM-DD",和标准时间格式:"HH:MM:SS"** @param date 标准日期格式 "YYYY-MM-DD"* @param time 标准时间格式 "HH:MM:SS"* @return java.util.Date*/public static Date toDate(String date, String time) {if (date == null || time == null)return null;int dateSlash1 = date.indexOf("-");int dateSlash2 = date.lastIndexOf("-");if (dateSlash1 <= 0 || dateSlash1 == dateSlash2)return null;int timeColon1 = time.indexOf(":");int timeColon2 = time.lastIndexOf(":");if (timeColon1 <= 0 || timeColon1 == timeColon2)return null;String year = date.substring(0, dateSlash1);String month = date.substring(dateSlash1 + 1, dateSlash2);String day = date.substring(dateSlash2 + 1);String hour = time.substring(0, timeColon1);String minute = time.substring(timeColon1 + 1, timeColon2);String second = time.substring(timeColon2 + 1);;return toDate(year, month, day, hour, minute, second);}/*** 通过标准时间输入,年,月,日,时,分,秒,生成java.util.Date** @param yearStr 年* @param monthStr 月* @param dayStr 日* @param hourStr 时* @param minuteStr 分* @param secondStr 秒* @return java.util.Date*/public static Date toDate(String yearStr, String monthStr,String dayStr, String hourStr, String minuteStr, String secondStr) {int year, month, day, hour, minute, second;try {year = Integer.parseInt(yearStr);month = Integer.parseInt(monthStr);day = Integer.parseInt(dayStr);hour = Integer.parseInt(hourStr);minute = Integer.parseInt(minuteStr);second = Integer.parseInt(secondStr);} catch (Exception e) {return null;}return toDate(year, month, day, hour, minute, second);}/*** 通过标准时间输入,年,月,日,时,分,秒,生成java.util.Date** @param year 年* @param month 月* @param day 日* @param hour 时* @param minute 分* @param second 秒* @return java.util.Date*/public static Date toDate(int year, int month, int day, int hour,int minute, int second) {Calendar calendar = Calendar.getInstance();try {calendar.set(year, month - 1, day, hour, minute, second);} catch (Exception e) {return null;}return calendar.getTime();}/*** 生成标准格式的字符串 格式为: "MM-DD-YYYY HH:MM:SS"** @param date The Date* @return 生成默认格式的字符串 格式为: "MM-DD-YYYY HH:MM:SS"*/public static String toDateTimeString(Date date) {if (date == null)return "";String dateString = toDateString(date);String timeString = toTimeString(date);if (dateString == null || timeString == null)return "";return dateString + " " + timeString;}/*** 生成标准日期,格式为 YYYY+spe+MM+spe+DD** @param date The Date* @return 生成日期, 格式为 YYYY+spe+MM+spe+DD*/public static String toDateString(Date date, String spe) {if (date == null)return "";Calendar calendar = Calendar.getInstance();calendar.setTime(date);int month = calendar.get(Calendar.MONTH) + 1;int day = calendar.get(Calendar.DAY_OF_MONTH);int year = calendar.get(Calendar.YEAR);String monthStr = "" + month;String dayStr = "" + day;String yearStr = "" + year;if (month < 10)monthStr = "0" + month;if (day < 10)dayStr = "0" + day;return yearStr + spe + monthStr + spe + dayStr;}/*** 生成标准日期,格式为 YYYY-MM-DD** @param date The Date* @return 生成日期, 格式为 YYYY-MM-DD*/public static String toDateString(Date date) {return toDateString(date, "-");}/*** 根据输入的时间,生成时间格式 HH:MM:SS** @param date java.util.Date* @return 生成时间格式为 HH:MM:SS*/public static String toTimeString(Date date) {if (date == null)return "";Calendar calendar = Calendar.getInstance();calendar.setTime(date);return toTimeString(calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));}/*** 根据输入的时,分,秒,生成时间格式 HH:MM:SS** @param hour 时* @param minute 分* @param second 秒* @return 生成时间格式为 HH:MM:SS*/public static String toTimeString(int hour, int minute, int second) {String hourStr = "" + hour;String minuteStr = "" + minute;String secondStr = "" + second;if (hour < 10)hourStr = "0" + hour;if (minute < 10)minuteStr = "0" + minute;if (second < 10)secondStr = "0" + second;return hourStr + ":" + minuteStr + ":" + secondStr;}/*** 取得给定日历,给定格式的日期字符串** @param calendar 日历,给定一个日历* @return String 取得默认的日期时间字符串"yyyy-MM-dd"*/public static String toDateString(Calendar calendar) {return FORMAT_YYYY_MM_DD.format(calendar.getTime());}/*** 取得给定日历,给定格式的日期时间字符串** @param calendar 日历,给定一个日历* @return String 取得默认的日期时间字符串"yyyy-MM-dd HH:mm:ss"*/public static String toDateTimeString(Calendar calendar) {return FORMAT_YYYY_MM_DDHHMMSS.format(calendar.getTime());}/*** 取得给定日历,给定格式的日期时间字符串** @param calendar 日历,给定一个日历* @param format 格式,如String format = "yyyy-MM-dd HH:mm:ss";* @return String 取得给定日历,给定格式的日期时间字符串*/public static String toDateTimeString(Calendar calendar, String format) {return toDateTimeString(calendar.getTime(), format);}/*** 取得给定时间,给定格式的日期时间字符串,标准格式:"yyyy-MM-dd HH:mm:ss";** @param datetime 日期,给定一个时间的毫秒数* @return String 取得给定时间,给定格式的日期时间字符串*/public static String toDateTimeString(long datetime) {return FORMAT_YYYY_MM_DDHHMMSS.format(new Date(datetime));}/*** 取得给定时间,给定格式的日期时间字符串,标准格式:"yyyy-MM-dd HH:mm:ss.SSS";** @param datetime 日期,给定一个时间的毫秒数* @return String 取得给定时间,给定格式的日期时间字符串*/public static String toDateTimeString2(long datetime) {return FORMAT_YYYY_MM_DDHHMMSSSSS.format(new Date(datetime));}/*** 取得给定时间,给定格式的日期时间字符串** @param datetime 日期,给定一个时间的毫秒数* @param format 格式,如String format = "yyyy-MM-dd HH:mm:ss";* @return String 取得给定时间,给定格式的日期时间字符串*/public static String toDateTimeString(long datetime, String format) {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(new Date(datetime));}/*** 取得给定时间,给定格式的日期时间字符串** @param date 日期,给定一个时间* @param format 格式,如String format = "yyyy-MM-dd HH:mm:ss";* @return String 取得给定时间,给定格式的日期时间字符串*/public static String toDateTimeString(Date date, String format) {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(date);}/*** 取得当前的日期时间字符串** @param format 格式,如String format = "yyyy-MM-dd HH:mm:ss";* @return String 取得当前的日期时间字符串*/public static String getDateTimeString(String format) {return toDateTimeString(new Date(), format);}/*** 取得当前的日期时间字符串yyyy-MM-dd HH:mm:ss** @return String 取得当前的日期时间字符串YYYY-MM-DD HH:mm:ss*/public static String getDateTimeString() {return FORMAT_YYYY_MM_DDHHMMSS.format(nowDate());}/*** 取得当前的日期时间字符串YYYY/MM/DD HH:mm:ss (移动)** @return String 取得当前的日期时间字符串YYYY/MM/DD HH:mm:ss*/public static String getDateTimeString2() {String format = "yyyy/MM/dd HH:mm:ss";return getDateTimeString(format);}/*** 取得当前的日期时间字符串yyyy-MM-dd HH:mm:ss.SSS** @return String 取得当前的日期时间字符串YYYY-MM-DD HH:mm:ss.SSS*/public static String getDateTimeString3() {return FORMAT_YYYY_MM_DDHHMMSSSSS.format(nowDate());}/*** 取得当前的日期时间字符串YYYY/MM/DD (移动)** @return String 取得当前的日期时间字符串YYYY/MM/DD*/public static String getDateString2() {String format = "yyyy/MM/dd";return getDateTimeString(format);}/*** 取得当前的日期时间字符串yyyyMMddHHmmss** @return String 取得当前的日期时间字符串yyyyMMddHHmmss*/public static String getDateTime14String() {return FORMAT_YYYYMMDDHHMMSS14.format(nowDate());}/*** 取得当前的日期时间字符串yyyyMMddHHmmssSSS** @return String 取得当前的日期时间字符串yyyyMMddHHmmssSSS*/public static String getDateTime17String() {return FORMAT_YYYYMMDDHHMMSS17.format(nowDate());}/*** 取得当前的日期时间字符串YYMMDDHHMISS** @return String 取得当前的日期时间字符串YYMMDDHHMISS*/public static String getDateTime12String() {return FORMAT_YYMMDDHHMMSS12.format(nowDate());}/*** 取得当前的日期时间字符串YYYYMMDD** @return String 取得当前的日期时间字符串*/public static String getDateTime8String() {return FORMAT_YYYYMMDD8.format(nowDate());}/*** 取得当前的日期时间字符串YYYY-MM** @return String 取得当前的日期时间字符串*/public static String getDateTime7String() {return FORMAT_YYYY_MM.format(nowDate());}/*** 取得当前的日期时间字符串YYYYMM** @return String 取得当前的日期时间字符串*/public static String getDateTime6String() {return FORMAT_YYYYMM6.format(nowDate());}/*** 取得当前的日期时间字符串YYYY-MM-DD** @return String 取得当前的日期时间字符串*/public static String getDateString() {return FORMAT_YYYY_MM_DD.format(nowDate());}/*** 取得当前的日期时间字符串HH:mm:ss** @return String 取得当前的日期时间字符串*/public static String getTimeString() {return FORMAT_HHMMSS8.format(nowDate());}/*** 取得当前的日期整型数组共7项,分别为年,月,日,时,分,秒,毫秒** @return int[] 共7项,分别为年,月,日,时,分,秒,毫秒*/public static int[] getDateTimes() {int[] dates = new int[7];Calendar calendar = Calendar.getInstance();dates[0] = calendar.get(Calendar.YEAR);dates[1] = calendar.get(Calendar.MONTH) + 1;dates[2] = calendar.get(Calendar.DAY_OF_MONTH);dates[3] = calendar.get(Calendar.HOUR_OF_DAY);dates[4] = calendar.get(Calendar.MINUTE);dates[5] = calendar.get(Calendar.SECOND);dates[6] = calendar.get(Calendar.MILLISECOND);return dates;}/*** 通过标准时间输入,年,月,日,时,分,秒,生成java.util.Date** @param yearStr 年* @param monthStr 月* @param dayStr 日* @param hourStr 时* @param minuteStr 分* @param secondStr 秒* @return Calendar*/public static Calendar toCalendar(String yearStr, String monthStr,String dayStr, String hourStr, String minuteStr, String secondStr) {int year, month, day, hour, minute, second;try {year = Integer.parseInt(yearStr);month = Integer.parseInt(monthStr);day = Integer.parseInt(dayStr);hour = Integer.parseInt(hourStr);minute = Integer.parseInt(minuteStr);second = Integer.parseInt(secondStr);} catch (Exception e) {return null;}return toCalendar(year, month, day, hour, minute, second);}/*** 通过String,组织一个日历** @param datetime* @return 通过整型数组, 返回一个日历*/public static Calendar toCalendar(String datetime) {int index = datetime.indexOf(" ");String date = datetime.substring(0, index);String time = datetime.substring(index + 1);int dateSlash1 = date.indexOf("-");int dateSlash2 = date.lastIndexOf("-");if (dateSlash1 <= 0 || dateSlash1 == dateSlash2)return null;int timeColon1 = time.indexOf(":");int timeColon2 = time.lastIndexOf(":");if (timeColon1 <= 0 || timeColon1 == timeColon2)return null;String yearStr = date.substring(0, dateSlash1);String monthStr = date.substring(dateSlash1 + 1, dateSlash2);String dayStr = date.substring(dateSlash2 + 1);String hourStr = time.substring(0, timeColon1);String minuteStr = time.substring(timeColon1 + 1, timeColon2);String secondStr = time.substring(timeColon2 + 1);;int year, month, day, hour, minute, second;try {year = Integer.parseInt(yearStr);month = Integer.parseInt(monthStr);day = Integer.parseInt(dayStr);hour = Integer.parseInt(hourStr);minute = Integer.parseInt(minuteStr);second = Integer.parseInt(secondStr);Calendar calendar = Calendar.getInstance();calendar.set(year, month - 1, day, hour, minute, second);return calendar;} catch (Exception e) {return null;}}/*** 通过整型数组,组织一个日历** @param dates* @return 通过整型数组, 返回一个日历*/public static Calendar toCalendar(int[] dates) {if (dates == null || dates.length < 6)return null;return toCalendar(dates[0], dates[1], dates[2], dates[3], dates[4],dates[5]);}/*** 通过标准时间输入,年,月,日,时,分,秒,生成java.util.Date** @param year 年* @param month 月* @param day 日* @param hour 时* @param minute 分* @param second 秒* @return Calendar*/public static Calendar toCalendar(int year, int month, int day, int hour,int minute, int second) {Calendar c = Calendar.getInstance();c.set(Calendar.YEAR, year);c.set(Calendar.MONTH, month - 1);c.set(Calendar.DATE, day);c.set(Calendar.HOUR_OF_DAY, hour);c.set(Calendar.MINUTE, minute);c.set(Calendar.SECOND, second);return c;}/*** 通过整型数组,组织一个日期** @param dates* @return 通过整型数组, 组织一个日期*/public static Date toDate(int[] dates) {if (dates == null || dates.length < 6)return null;return toCalendar(dates).getTime();}/*** 获取当前年** @return 当前年*/public static int getCurrentYear() {Calendar calendar = Calendar.getInstance();return calendar.get(Calendar.YEAR);}/*** 获取当前月份** @return 月份*/public static int getCurrentMonth() {Calendar calendar = Calendar.getInstance();return calendar.get(Calendar.MONTH) + 1;}/*** 获取当前月天数*/public static int getCurrentMonthDays() {Calendar calendar = Calendar.getInstance();int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH) + 1;return getMonthDays(year, month);}/*** 获取指定月天数,yyyyMM*/public static int getMonthDays(String yearMonth) {int year = Integer.parseInt(yearMonth.substring(0, 4));int month = Integer.parseInt(yearMonth.substring(4));return getMonthDays(year, month);}/*** 获取指定月天数*/public static int getMonthDays(int year, int month) {switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:return 31;case 4:case 6:case 9:case 11:return 30;default:// 2月boolean isLeapYear = ValidateUtils.isLeapYear(year);return isLeapYear ? 29 : 28;}}/*** 获取下一个年月,格式为yyyyMM*/public static String getNextYearMonth(String currentYearMonth) {int year = Integer.parseInt(currentYearMonth.substring(0, 4));int month = Integer.parseInt(currentYearMonth.substring(4));if (month == 12) {year += 1;month = 1;} else {month += 1;}StringBuffer strb = new StringBuffer().append(year);if (month > 9)strb.append(month);elsestrb.append("0").append(month);return strb.toString();}/*** 获取当前日期** @return 当前日期*/public static int getCurrentDay() {Calendar calendar = Calendar.getInstance();int day = calendar.get(Calendar.DAY_OF_MONTH);return day;}/*** 获取当前时** @return 当前时间,如:23点,0点,1点等*/public static int getCurrentHour() {Calendar calendar = Calendar.getInstance();int hour = calendar.get(Calendar.HOUR_OF_DAY);return hour;}/*** 获取当前分** @return 当前分*/public static int getCurrentMinute() {Calendar calendar = Calendar.getInstance();int hour = calendar.get(Calendar.MINUTE);return hour;}/*** 获取当前时间的星期数:星期日=7;星期一=1;星期二=2;星期三=3;星期四=4;星期五=5;星期六=6;** @return 周数值*/public static int getCurrentWeek() {Calendar calendar = Calendar.getInstance();int week = calendar.get(Calendar.DAY_OF_WEEK);week = week - 1;if (week == 0)week = 7;return week;}/*** 获取两个日期对象相差年数** @param date2 日期对象* @return int 年份差值* @parma date1 日期对象*/public static int compareYear(Date date1, Date date2) {if (date1 == null || date2 == null)return 0;Calendar calendar = Calendar.getInstance();calendar.setTime(date1);int year1 = calendar.get(Calendar.YEAR);calendar.setTime(date2);int year2 = calendar.get(Calendar.YEAR);return year1 - year2;}/*** 获取两个日期对象相差月数** @param date1 日期对象* @param date2 日期对象* @return int 月份差值*/public static int compareMonth(Date date1, Date date2) {if (date1 == null || date2 == null)return 0;int year = compareYear(date1, date2);Calendar calendar = Calendar.getInstance();calendar.setTime(date1);int month1 = calendar.get(Calendar.MONTH);calendar.setTime(date2);int month2 = calendar.get(Calendar.MONTH);/* 进行比较 */return 12 * year + (month1 - month2);}/*** 获取两个日期对象相差月数,大一整月才算大一个月** @param date1 字符串对象* @param date2 字符串对象* @return int 月份差值*/public static int compareMonth(String date1, String date2) {if (date1 == null || date2 == null)return 0;int year1 = Integer.parseInt(date1.substring(0, 4));int year2 = Integer.parseInt(date2.substring(0, 4));int month1 = Integer.parseInt(date1.substring(5, 7));int month2 = Integer.parseInt(date2.substring(5, 7));int day1 = Integer.parseInt(date1.substring(8, 10));int day2 = Integer.parseInt(date2.substring(8, 10));int value = (year1 - year2) * 12 + (month1 - month2);if (day1 < day2)value--;return value;}/*** 获取两个日期对象相差天数** @param date1str String yyyy-MM-dd* @param date2str String yyyy-MM-dd* @return int 日差值*/public static int compareDay(String date1str, String date2str) {if (date1str == null || date2str == null)return 0;Date date1 = toDate(date1str, "00:00:01");Date date2 = toDate(date2str, "00:00:00");return compareDay(date1, date2);}/*** 获取两个日期对象相差天数** @param date1 日期对象* @param date2 日期对象* @return int 日差值*/public static int compareDay(Date date1, Date date2) {if (date1 == null || date2 == null)return 0;long time1 = date1.getTime();long time2 = date2.getTime();long margin = time1 - time2;/* 转化成天数 */int ret = (int) Math.floor((double) margin / (1000 * 60 * 60 * 24));return ret;}/*** 获取两个日期对象相差天数** @param date1 日期对象* @param date2 日期对象* @return int 日差值*/public static int compareDayByDate(Date date1, Date date2) {if (date1 == null || date2 == null)return 0;Calendar aCalendar = Calendar.getInstance();aCalendar.setTime(date1);int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);aCalendar.setTime(date2);int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);int ret = day1 - day2;return ret;}/*** 获取两个日期对象相差的小时数** @param date1str String yyyy-MM-dd hh:mm:ss* @param date2str String yyyy-MM-dd hh:mm:ss* @return int 相差小时数*/public static int compareHour(String date1str, String date2str) {if (date1str == null || date2str == null)return 0;Date date1 = toDate(date1str);Date date2 = toDate(date2str);return compareHour(date1, date2);}/*** 获取两个日期对象相差的小时数** @param date1 日期对象* @param date2 日期对象* @return int 相差小时数*/public static int compareHour(Date date1, Date date2) {if (date1 == null || date2 == null)return 0;long time1 = date1.getTime();long time2 = date2.getTime();long margin = time1 - time2;int ret = (int) Math.floor((double) margin / (1000 * 60 * 60));return ret;}/*** 获取两个日期对象相差的分钟数** @param date1str String yyyy-MM-dd hh:mm:ss* @param date2str String yyyy-MM-dd hh:mm:ss* @return int 相差分钟数*/public static int compareMinute(String date1str, String date2str) {if (date1str == null || date2str == null)return 0;Date date1 = toDate(date1str);Date date2 = toDate(date2str);return compareMinute(date1, date2);}/*** 获取两个日期对象相差的分钟数** @param date1 日期对象* @param date2 日期对象* @return int 相差分钟数*/public static int compareMinute(Date date1, Date date2) {if (date1 == null || date2 == null)return 0;long time1 = date1.getTime() / 1000;long time2 = date2.getTime() / 1000;long margin = time1 - time2;int ret = (int) Math.floor((double) margin / 60);return ret;}/*** 获取两个日期对象相差秒数** @param date1str String yyyy-MM-dd hh:mm:ss* @param date2str String yyyy-MM-dd hh:mm:ss* @return int 相差秒数*/public static int compareSecond(String date1str, String date2str) {if (date1str == null || date2str == null)return 0;Date date1 = toDate(date1str);Date date2 = toDate(date2str);return compareSecond(date1, date2);}/*** 获取两个日期对象相差秒数** @param date1 日期对象* @param date2 日期对象* @return int 相差秒数*/public static int compareSecond(Date date1, Date date2) {if (date1 == null || date2 == null)return 0;long time1 = date1.getTime();long time2 = date2.getTime();long margin = time1 - time2;Long longValue = new Long(margin / (1000));return longValue.intValue();}/*** 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致** @param nowTime 当前时间* @param startTime 开始时间* @param endTime 结束时间* @return*/public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {return true;}Calendar date = Calendar.getInstance();date.setTime(nowTime);Calendar begin = Calendar.getInstance();begin.setTime(startTime);Calendar end = Calendar.getInstance();end.setTime(endTime);if (date.after(begin) && date.before(end)) {return true;} else {return false;}}/*** 获取和当前时间毫秒差值** @param dateTime YYYY-MM-DD hh:mm:ss* @return 毫秒差*/public static long getTimeMargin(String dateTime) {int index = dateTime.indexOf(" ");String date = dateTime.substring(0, index);String time = dateTime.substring(index + 1);int dateSlash1 = date.indexOf("-");int dateSlash2 = date.lastIndexOf("-");if (dateSlash1 <= 0 || dateSlash1 == dateSlash2)return -1;int timeColon1 = time.indexOf(":");int timeColon2 = time.lastIndexOf(":");if (timeColon1 <= 0 || timeColon1 == timeColon2)return -1;Calendar calendar = Calendar.getInstance();try {int year = Integer.parseInt(date.substring(0, dateSlash1));int month = Integer.parseInt(date.substring(dateSlash1 + 1, dateSlash2));int day = Integer.parseInt(date.substring(dateSlash2 + 1));int hour = Integer.parseInt(time.substring(0, timeColon1));int minute = Integer.parseInt(time.substring(timeColon1 + 1, timeColon2));int second = Integer.parseInt(time.substring(timeColon2 + 1));calendar.set(year, month - 1, day, hour, minute, second);} catch (Exception e) {return -1;}return System.currentTimeMillis() - calendar.getTimeInMillis();}public static String getFirstMonthDay() {String curYearMonth = getDateTimeString("yyyy-MM");return curYearMonth + "-01";}/*** 获取上一个月第一天 yyyy-MM-dd*/public static String getPreviosMonthFirstDay() {String curYearMonth = getDateTime6String();String yearMonth = getPreviousYearMonth(curYearMonth);return yearMonth.substring(0, 4) + "-" + yearMonth.substring(4) + "-01";}/*** 获到上一月最后一天yyyy-MM-dd*/public static String getPreviosMonthLastDay() {String curYearMonth = getDateTime6String();String yearMonth = getPreviousYearMonth(curYearMonth);return getLastMonthDay(yearMonth);}/*** 获到当前月最后一天yyyy-MM-dd*/public static String getLastMonthDay() {String curYearMonth = getDateTime6String();return getLastMonthDay(curYearMonth);}/*** 获到指定月最后一天yyyy-MM-dd*/public static String getLastMonthDay(String curYearMonth) {String yearStr = curYearMonth.substring(0, 4);String monthStr = curYearMonth.substring(4);int year = Integer.parseInt(yearStr);int month = Integer.parseInt(monthStr);switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:return yearStr + "-" + monthStr + "-31";case 4:case 6:case 9:case 11:return yearStr + "-" + monthStr + "-30";case 2:int day = ValidateUtils.isLeapYear(year) ? 29 : 28;return yearStr + "-" + monthStr + "-" + day;}return null;}/*** 获取上一个年月,格式为yyyyMM*/public static String getPreviousYearMonth(String currentYearMonth) {int year = Integer.parseInt(currentYearMonth.substring(0, 4));int month = Integer.parseInt(currentYearMonth.substring(4));if (month == 1) {year -= 1;month = 12;} else {month -= 1;}StringBuffer strb = new StringBuffer().append(year);if (month > 9)strb.append(month);elsestrb.append("0").append(month);return strb.toString();}/*** 获取当前时间的前一天或数天的年、月、日,并以数组形式还回。 数组0为年;1为月;2为日** @param year 当前年* @param month 当前月* @param day 当前日期* @param days 相差天数* @return 年、月、日数组*/public static int[] getPreviousDay(int year, int month, int day, int days) {Calendar calendar = Calendar.getInstance();calendar.set(year, month - 1, day);long longDate = (calendar.getTime()).getTime()- (1000 * 60 * 60 * 24 * days);Date date = new Date(longDate);calendar.setTime(date);int[] rtn = new int[3];rtn[0] = calendar.get(Calendar.YEAR);rtn[1] = calendar.get(Calendar.MONTH) + 1;rtn[2] = calendar.get(Calendar.DATE);return rtn;}/*** 获取前几月对应的当前时间** @param months 相差月数* @return String yyyy-MM-dd*/public static String getPreviousDateStringByMonth(int months) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.MONTH, -months);return toDateString(calendar);}/*** 获取指定时间前几月的时间** @param datetime 指定时间* @param months 相差月数* @return String yyyy-MM-dd*/public static String getPreviousDateStringByMonth(String datetime, int months) {Calendar calendar = toCalendar(datetime);calendar.add(Calendar.MONTH, -months);return toDateString(calendar);}/*** 获取前几月对应的当前时间** @param months 相差月数* @return String yyyy-MM-dd HH:mm:ss*/public static String getPreviousDateTimeStringByMonth(int months) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.MONTH, -months);return toDateTimeString(calendar);}/*** 获取指定时间前几月的时间** @param datetime 指定时间* @param months 相差月数* @return String yyyy-MM-dd HH:mm:ss*/public static String getPreviousDateTimeStringByMonth(String datetime,int months) {Calendar calendar = toCalendar(datetime);calendar.add(Calendar.MONTH, -months);return toDateTimeString(calendar);}/*** 获取前几天对应的当前时间** @param days 相差天数* @return String yyyy-MM-dd*/public static String getPreviousDateString(int days) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.DAY_OF_MONTH, -days);return toDateString(calendar);}/*** 获取指定时间前几天的时间** @param datetime 指定时间* @param days 相差天数* @return String yyyy-MM-dd*/public static String getPreviousDateString(String datetime, int days) {Calendar calendar = toCalendar(datetime);calendar.add(Calendar.DAY_OF_MONTH, -days);return toDateString(calendar);}/*** 获取前几天对应的当前时间** @param days 相差天数* @return String yyyy-MM-dd HH:mm:ss*/public static String getPreviousDateTimeString(int days) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.DAY_OF_MONTH, -days);return toDateTimeString(calendar);}/*** 获取指定时间前几天的时间** @param datetime 指定时间* @param days 相差天数* @return String yyyy-MM-dd HH:mm:ss*/public static String getPreviousDateTimeString(String datetime, int days) {Calendar calendar = toCalendar(datetime);calendar.add(Calendar.DAY_OF_MONTH, -days);return toDateTimeString(calendar);}/*** 获取前几小时对应的当前时间** @param hours 相差小时数* @return String yyyy-MM-dd*/public static String getPreviousDateByHourString(int hours) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.HOUR_OF_DAY, -hours);return toDateString(calendar);}/*** 获取前几小时对应的当前时间** @param hours 相差小时数* @return String yyyy-MM-dd HH:mm:ss*/public static String getPreviousDateTimeByHourString(int hours) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.HOUR_OF_DAY, -hours);return toDateTimeString(calendar);}/*** 获取指定时间前几小时的时间** @param datetime 指定时间* @param hours 相差小时数* @return String yyyy-MM-dd HH:mm:ss*/public static String getPreviousDateTimeByHourString(String datetime,int hours) {Calendar calendar = toCalendar(datetime);calendar.add(Calendar.HOUR_OF_DAY, -hours);return toDateTimeString(calendar);}/*** 获取前几秒对应的当前时间** @param second 秒数* @return String yyyy-MM-dd*/public static String getPreviousDateBySecondString(int second) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.SECOND, -second);return toDateString(calendar);}/*** 获取前几秒对应的当前时间** @param second 秒数* @return String yyyy-MM-dd HH:mm:ss*/public static String getPreviousDateTimeBySecondString(int second) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.SECOND, -second);return toDateTimeString(calendar);}/*** 获取指定时间前几秒的时间** @param datetime 指定时间* @param second 秒数* @return String yyyy-MM-dd HH:mm:ss*/public static String getPreviousDateTimeBySecondString(String datetime,int second) {Calendar calendar = toCalendar(datetime);calendar.add(Calendar.SECOND, -second);return toDateTimeString(calendar);}/*** 获取前一天对应的当前时间,采用标准格式yyyy-MM-dd** @return String*/public static String getPreviousDateString() {return getPreviousDateTimeString("yyyy-MM-dd");}/*** 获取前一天对应的当前时间,采用短信格式yyyy/MM/dd** @return String*/public static String getPreviousDateString2() {return getPreviousDateTimeString("yyyy/MM/dd");}/*** 获取前一天对应的当前时间** @param format 格式化如 yyyy-MM-dd HH:mm:ss* @return String*/public static String getPreviousDateTimeString(String format) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.DAY_OF_MONTH, -1);return toDateTimeString(calendar, format);}/*** 获取前一天对应的当前时间,采用标准格式yyyy-MM-dd HH:mm:ss** @return String*/public static String getPreviousDateTimeString() {return getPreviousDateTimeString("yyyy-MM-dd HH:mm:ss");}/*** 获取前一天对应的当前时间,采用短信格式yyyy/MM/dd HH:mm:ss** @return String*/public static String getPreviousDateTimeString2() {return getPreviousDateTimeString("yyyy/MM/dd HH:mm:ss");}/*** 获到下一个月份yyyy-MM, curYearMonth格式yyyyMM或yyyy-MM*/public static String getNextMonthSpe(String curYearMonth) {curYearMonth = curYearMonth.replace("-", "");String yearMonth = getNextMonth(curYearMonth);return yearMonth.substring(0, 4) + "-" + yearMonth.substring(4);}/*** 获到下一个月份yyyyMM, curYearMonth格式yyyyMM*/public static String getNextMonth(String curYearMonth) {int year = Integer.parseInt(curYearMonth.substring(0, 4));int month = Integer.parseInt(curYearMonth.substring(4));if (month == 12) {year += 1;month = 1;} else {month += 1;}StringBuffer strb = new StringBuffer().append(year);if (month > 9)strb.append(month);elsestrb.append("0").append(month);return strb.toString();}/*** 获取后一天的Date String** @param spe 分隔符* @return YYYY+spe+MM+spe+DD*/public static String getNextDateStr(String spe) {Calendar calendar = Calendar.getInstance();long longDate = (calendar.getTime()).getTime()+ (1000 * 60 * 60 * 24 * 1);Date date = new Date(longDate);calendar.setTime(date);return toDateString(calendar.getTime(), spe);}/*** 获取指定时间的后一天的Date String** @param currentDate* @return YYYY+spe+MM+spe+DD*/public static String getNextDateString(String currentDate) {Calendar calendar = toCalendar(currentDate + " 00:00:01");calendar.add(Calendar.DAY_OF_MONTH, 1);return toDateString(calendar);}/*** 获取后几年对应的当前时间** @return String*/public static String getNextDateStringAddYeah(int years) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.YEAR, years);return toDateString(calendar);}/*** 获取后几月对应的当前时间** @return String*/public static String getNextDateStringAddMonth(int months) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.MONTH, months);return toDateString(calendar);}/*** 获取指定日期的后几月日期** @param currentDate 指定日期* @param months 指定月数* @return yyyy-MM-dd* @throws Exception*/public static String getNextDateStringAddMonth(String currentDate,int months) {int year = Integer.parseInt(currentDate.substring(0, 4));int month = Integer.parseInt(currentDate.substring(5, 7));int day = Integer.parseInt(currentDate.substring(8));Calendar calendar = Calendar.getInstance();calendar.set(year, month - 1, day);calendar.add(Calendar.MONTH, months);return toDateString(calendar);}/*** 获取后几天对应的当前时间** @return String*/public static String getNextDateStringAddDay(int days) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.DAY_OF_MONTH, days);return toDateString(calendar);}/*** 获取指定日期的后几天日期** @param currentDate 指定日期* @param days 指定天数* @return yyyy-MM-dd* @throws Exception*/public static String getNextDateStringAddDay(String currentDate, int days) {int year = Integer.parseInt(currentDate.substring(0, 4));int month = Integer.parseInt(currentDate.substring(5, 7));int day = Integer.parseInt(currentDate.substring(8));Calendar calendar = Calendar.getInstance();calendar.set(year, month - 1, day);calendar.add(Calendar.DAY_OF_YEAR, days);return toDateString(calendar);}/*** 获取后几天对应的当前时间** @return String*/public static String getNextDateTimeString(int days) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.DAY_OF_MONTH, days);return toDateTimeString(calendar);}/*** 获取后几小时对应的当前时间** @return String*/public static String getNextDateStringByHour(int hours) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.HOUR_OF_DAY, hours);return toDateString(calendar);}/*** 获取后几小时对应的当前时间** @return String*/public static String getNextDateTimeStringByHour(int hours) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.HOUR_OF_DAY, hours);return toDateTimeString(calendar);}/*** 获取后几秒对应的当前时间** @return String*/public static String getNextDateStringBySecond(int seconds) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.SECOND, seconds);return toDateString(calendar);}/*** 获取后几秒对应的当前时间** @return String*/public static String getNextDateTimeStringBySecond(int seconds) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.SECOND, seconds);return toDateTimeString(calendar);}/*** 获取后一天的Date String** @param format 格式化* @return YYYY+spe+MM+spe+DD*/public static String getNextDateTimeStr(String format) {Calendar calendar = Calendar.getInstance();long longDate = (calendar.getTime()).getTime() + (1000 * 60 * 60 * 24 * 1);Date date = new Date(longDate);calendar.setTime(date);return toDateTimeString(calendar.getTime(), format);}/*** 获取后一天String** @return 年、月、日数组*/public static int[] getNextDay() {Calendar calendar = Calendar.getInstance();long longDate = (calendar.getTime()).getTime() + (1000 * 60 * 60 * 24 * 1);Date date = new Date(longDate);calendar.setTime(date);int[] rtn = new int[3];rtn[0] = calendar.get(Calendar.YEAR);rtn[1] = calendar.get(Calendar.MONTH) + 1;rtn[2] = calendar.get(Calendar.DATE);return rtn;}/*** 获取当前时间的后一天或数天的年、月、日,并以数组形式还回。 数组0为年;1为月;2为日** @param year 当前年* @param month 当前月* @param day 当前日期* @param days 相差天数* @return 年、月、日数组*/public static int[] getNextDay(int year, int month, int day, int days) {Calendar calendar = Calendar.getInstance();calendar.set(year, month - 1, day);long longDate = (calendar.getTime()).getTime() + (1000 * 60 * 60 * 24 * days);Date date = new Date(longDate);calendar.setTime(date);int[] rtn = new int[3];rtn[0] = calendar.get(Calendar.YEAR);rtn[1] = calendar.get(Calendar.MONTH) + 1;rtn[2] = calendar.get(Calendar.DATE);return rtn;}/*** 获取指定时间所在周的第一天的时间** @param year 年* @param month 月* @param day 日* @return 年、月、日数组*/public static int[] getDayOfWeek(int year, int month, int day) {int[] rtn = new int[6];int week = 0;long longDate = 0;Date date = null;Calendar calendar1 = Calendar.getInstance();Calendar calendar2 = Calendar.getInstance();Calendar calendar = Calendar.getInstance();calendar.set(year, month - 1, day);calendar.setFirstDayOfWeek(Calendar.SUNDAY);week = calendar.get(Calendar.DAY_OF_WEEK);longDate = (calendar.getTime()).getTime() - (60 * 1000 * 60 * 24 * (week - 1));date = new Date(longDate);calendar1.setTime(date);rtn[0] = calendar1.get(Calendar.YEAR);rtn[1] = calendar1.get(Calendar.MONTH) + 1;rtn[2] = calendar1.get(Calendar.DATE);longDate = (calendar.getTime()).getTime() + (60 * 1000 * 60 * 24 * (7 - week));date = new Date(longDate);calendar2.setTime(date);rtn[3] = calendar2.get(Calendar.YEAR);rtn[4] = calendar2.get(Calendar.MONTH) + 1;rtn[5] = calendar2.get(Calendar.DATE);return rtn;}/*********************************************************/// 以下为数据库使用的日期方法,Timestamp ,java.sql.Date/*********************************************************//*** 返回当前时间的Timestamp*/public static Timestamp nowTimestamp() {return new Timestamp(System.currentTimeMillis());}/*** 返回从当日开始的Timestamp*/public static Timestamp getDayStart(Timestamp stamp) {return getDayStart(stamp, 0);}/*** 返回多少天后开始的Timestamp*/public static Timestamp getDayStart(Timestamp stamp, int daysLater) {Calendar tempCal = Calendar.getInstance();tempCal.setTime(new Date(stamp.getTime()));tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH),tempCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);tempCal.add(Calendar.DAY_OF_MONTH, daysLater);return new Timestamp(tempCal.getTime().getTime());}/*** 返回下一天开始的Timestamp*/public static Timestamp getNextDayStart(Timestamp stamp) {return getDayStart(stamp, 1);}/*** 返回从当日结束的Timestamp*/public static Timestamp getDayEnd(Timestamp stamp) {return getDayEnd(stamp, 0);}/*** 返回从多少日后结束的Timestamp*/public static Timestamp getDayEnd(Timestamp stamp, int daysLater) {Calendar tempCal = Calendar.getInstance();tempCal.setTime(new Date(stamp.getTime()));tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH),tempCal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);tempCal.add(Calendar.DAY_OF_MONTH, daysLater);return new Timestamp(tempCal.getTime().getTime());}/*** String到java.sql.Date的转换 标准格式:YYYY-MM-DD** @param date The date String* @return java.sql.Date*/public static java.sql.Date toSqlDate(String date) {Date newDate = toDate(date, "00:00:00");if (newDate == null)return null;return new java.sql.Date(newDate.getTime());}/*** 生成java.sql.Date,通过传入year, month, day** @param yearStr 年* @param monthStr 月* @param dayStr 日* @return A java.sql.Date*/public static java.sql.Date toSqlDate(String yearStr, String monthStr,String dayStr) {Date newDate = toDate(yearStr, monthStr, dayStr, "0", "0","0");if (newDate == null)return null;return new java.sql.Date(newDate.getTime());}/*** 生成java.sql.Date,通过传入year, month, day** @param year 年* @param month 月* @param day 日* @return A java.sql.Date*/public static java.sql.Date toSqlDate(int year, int month, int day) {Date newDate = toDate(year, month, day, 0, 0, 0);if (newDate == null)return null;return new java.sql.Date(newDate.getTime());}/*** 转换String 到 java.sql.Time,格式:"HH:MM:SS"** @param time The time String* @return A java.sql.Time*/public static java.sql.Time toSqlTime(String time) {Date newDate = toDate("1970-1-1", time);if (newDate == null)return null;return new java.sql.Time(newDate.getTime());}/*** 生成 java.sql.Time 通过输入时,分,秒** @param hourStr 时* @param minuteStr 分* @param secondStr 秒* @return A java.sql.Time*/public static java.sql.Time toSqlTime(String hourStr, String minuteStr,String secondStr) {Date newDate = toDate("0", "0", "0", hourStr, minuteStr,secondStr);if (newDate == null)return null;return new java.sql.Time(newDate.getTime());}/*** 生成 java.sql.Time 通过输入时,分,秒** @param hour int 时* @param minute int 分* @param second 秒* @return A java.sql.Time*/public static java.sql.Time toSqlTime(int hour, int minute, int second) {Date newDate = toDate(0, 0, 0, hour, minute, second);if (newDate == null)return null;return new java.sql.Time(newDate.getTime());}/*** 转换String 到 java.sql.Timestamp,格式:"YYYY-MM-DD HH:MM:SS"** @param dateTime 格式:"YYYY-MM-DD HH:MM:SS"* @return Timestamp*/public static Timestamp toTimestamp(String dateTime) {Date newDate = toDate(dateTime);if (newDate == null)return null;return new Timestamp(newDate.getTime());}/*** 转换String 到 java.sql.Timestamp,格式:"YYYY-MM-DD HH:MM:SS"** @param date The date String: YYYY-MM-DD* @param time The time String: HH:MM:SS* @return Timestamp*/public static Timestamp toTimestamp(String date, String time) {Date newDate = toDate(date, time);if (newDate == null)return null;return new Timestamp(newDate.getTime());}/*** 生成 Timestamp 通过输入年,月,日,时,分,秒** @param yearStr 年* @param monthStr 月* @param dayStr 日* @param hourStr 时* @param minuteStr 分* @param secondStr T秒* @return Timestamp*/public static Timestamp toTimestamp(String yearStr, String monthStr,String dayStr, String hourStr, String minuteStr, String secondStr) {Date newDate = toDate(yearStr, monthStr, dayStr, hourStr,minuteStr, secondStr);if (newDate == null)return null;return new Timestamp(newDate.getTime());}/*** 生成 Timestamp 通过输入年,月,日,时,分,秒** @param year 年 int* @param month 月 int* @param day 日 int* @param hour 时 int* @param minute 分 int* @param second 秒 int* @return Timestamp*/public static Timestamp toTimestamp(int year, int month, int day, int hour,int minute, int second) {Date newDate = toDate(year, month, day, hour, minute, second);if (newDate == null)return null;return new Timestamp(newDate.getTime());}public static List<String> process(String startDate, String endDate) {List<String> al = new ArrayList<String>();if (startDate.equals(endDate)) {// IF起始日期等于截止日期,仅返回起始日期一天al.add(startDate);} else if (startDate.compareTo(endDate) < 0) {// IF起始日期早于截止日期,返回起止日期的每一天while (startDate.compareTo(endDate) < 0) {al.add(startDate);try {Long l = FORMAT_YYYY_MM_DD.parse(startDate).getTime();startDate = FORMAT_YYYY_MM_DD.format(l + 3600 * 24 * 1000);// +1天} catch (Exception e) {e.printStackTrace();}}} else {// IF起始日期晚于截止日期,仅返回起始日期一天al.add(startDate);}return al;}
}
3、JSON格式化工具类
3.1、JsonUtils
package com.study.java8.util;import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;/*** @Description: json格式化工具类* @Author: jsz* @date: 2023/9/9 11:11*/
public class JsonUtils {/** logger */private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);private static final ObjectMapper objectMapper;static {objectMapper = new ObjectMapper();// 如果为空则不输出//objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);// 对于空的对象转json的时候不抛出错误objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);// 禁用序列化日期为timestampsobjectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);// 禁用遇到未知属性抛出异常objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);// 视空字符传为nullobjectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);// 低层级配置objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);// 允许属性名称没有引号objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);// 允许单引号objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);// 取消对非ASCII字符的转码objectMapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false);}/*** 字符串转jsonNode* @param json * @return*/public static JsonNode strToJsonNode(String json) {try {return objectMapper.readTree(json);} catch (IOException e) {logger.error("strToJsonNode Json格式化异常", e);}return null;}/*** 转成Json字符串* @return*/public static String toJsonString(Object object) {if (object != null) {try {return objectMapper.writeValueAsString(object);} catch (IOException e) {logger.error("toJsonString Json格式化异常", e);}}return null;}public static <T> T readJson2Bean(String jsonString, Class<T> valueType) {if (org.apache.commons.lang3.StringUtils.isNotBlank(jsonString)) {try {return objectMapper.readValue(jsonString, valueType);} catch (IOException e) {logger.error("readJson2Bean Json格式化异常", e);}}return null;}public static <T> T readJson2Bean(String jsonString, TypeReference<T> ref) {if (org.apache.commons.lang3.StringUtils.isNotBlank(jsonString)) {try {return objectMapper.readValue(jsonString, ref);} catch (IOException e) {logger.error("readJson2Bean Json格式化异常", e);}}return null;}public static <T> List<T> readJson2List(String jsonString, Class<T> elementClass) {if (jsonString == null || "".equals(jsonString)) {return null;} else {JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, elementClass);try {return (List<T>) objectMapper.readValue(jsonString, javaType);} catch (IOException e) {logger.error("decodeJsonToList Json格式化异常", e);return null;}}}/*** 对象转换** @param fromValue 输入对象* @param toValueType 输出对象*/public static <T> T convertValue(Object fromValue, Class<T> toValueType) {return objectMapper.convertValue(fromValue, toValueType);}/*** 对象转换** @param fromValue 输入对象* @param toValueTypeRef 输出对象*/public static <T> T convertValue(Object fromValue, TypeReference<T> toValueTypeRef) {return objectMapper.convertValue(fromValue, toValueTypeRef);}/*** 数据转换成map* @return*/public static Map<String, Object> getMapByStr(String dataObject) {if (StrUtils.isNotBlank(dataObject)) {try {return objectMapper.readValue(dataObject, new TypeReference<Map<String, Object>>(){});} catch (IOException e) {logger.error("getMapByStr Json格式化异常", e);}}return null;}}
4、http请求工具类
4.1、HttpUtils
package com.study.java8.util;import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;/*** @Description: HTTP请求工具类* @Author: jsz* @date: 2023/9/9 11:13*/
@Component
public class HttpUtils {/** logger */private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);private static RequestConfig requestConfig;private static final int MIN_TIMEOUT = 20000;private static final int MAX_TIMEOUT = 30000;static {RequestConfig.Builder configBuilder = RequestConfig.custom();// 设置连接超时configBuilder.setConnectTimeout(MIN_TIMEOUT);// 设置读取超时configBuilder.setSocketTimeout(MAX_TIMEOUT);// 设置从连接池获取连接实例的超时configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);requestConfig = configBuilder.build();}/*** 获取请求消息体* @param request* @return*/public static String getHttpBody(HttpServletRequest request){String str = null;try {// 获取输入流BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));// 写入数据到StringbuilderStringBuilder sb = new StringBuilder();String line = null;while ((line = streamReader.readLine()) != null) {sb.append(line);}str = sb.toString();} catch (Exception e) {e.printStackTrace();}return str;}/*** 发送 GET 请求(HTTP),不带输入数据* @param url* @param headers* @return*/public static String doGet(String url, Map<String, String> headers) {return doGet(url, new HashMap<String, Object>(), headers, false);}/*** 发送 GET 请求(HTTP),K-V形式* @param url* @param params* @param headers* @return*/public static String doGet(String url, Map<String, Object> params, Map<String, String> headers) {return doGet(url, params, headers, false);}/*** 发送 GET 请求(HTTP),不带输入数据* @param url* @param headers* @param isLongTerm 是否长期日志* @return*/public static String doGet(String url, Map<String, String> headers, boolean isLongTerm) {return doGet(url, new HashMap<String, Object>(), headers, isLongTerm);}/*** 发送 GET 请求(HTTP),K-V形式* @param url* @param params* @param headers* @return*/public static String doGet(String url, Map<String, Object> params, Map<String, String> headers, boolean isLongTerm) {String apiUrl = url;StringBuffer param = new StringBuffer();int i = 0;for (String key : params.keySet()) {if (i == 0) {param.append("?");} else {param.append("&");}param.append(key).append("=").append(params.get(key));i++;}apiUrl += param;String result = null;CloseableHttpClient httpclient = HttpClients.createDefault();try {HttpGet httpGet = new HttpGet(apiUrl);if (headers != null) {for (String key : headers.keySet()) {httpGet.addHeader(key, headers.get(key));}}httpGet.setConfig(requestConfig);HttpResponse response = httpclient.execute(httpGet);HttpEntity entity = response.getEntity();if (entity != null) {InputStream instream = entity.getContent();result = IOUtils.toString(instream, "UTF-8");}} catch (IOException e) {e.printStackTrace();}return result;}/*** 发送 POST 请求(HTTP),K-V形式* @param apiUrl API接口URL* @param params 参数jsonMap* @return*/public static String doPost(String apiUrl, Map<String, Object> params, Map<String, String> headers) {return doPost(apiUrl, JsonUtils.toJsonString(params) ,headers, false);}/*** 发送 POST 请求(HTTP),K-V形式* @param apiUrl API接口URL* @param params 参数jsonMap* @param isLongTerm 是否长期日志* @return*/public static String doPost(String apiUrl, Map<String, Object> params, Map<String, String> headers, boolean isLongTerm) {return doPost(apiUrl, JsonUtils.toJsonString(params) ,headers, isLongTerm);}/*** 发送 POST 请求(HTTP),JSON形式* @param apiUrl* @param json json对象* @param headers* @return*/public static String doPost(String apiUrl, String json, Map<String, String> headers, boolean isLongTerm) {CloseableHttpClient httpClient = HttpClients.createDefault();String httpStr = null;HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;try {if (headers != null) {for (String key : headers.keySet()) {httpPost.addHeader(key, headers.get(key));}}httpPost.setConfig(requestConfig);StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题stringEntity.setContentEncoding("UTF-8");stringEntity.setContentType("application/json");httpPost.setEntity(stringEntity);response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();if (entity != null) {httpStr = EntityUtils.toString(entity, "UTF-8");}} catch (Exception e) {logger.error("requestUrl: {}, requestBody: {}, requestHeader: {},requestError: {}", apiUrl, json, headers.toString(),e.getMessage());e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 远程读取文件流* @param netUrl* @return*/public static InputStream getFileInputStream(String netUrl) {return getFileInputStream(netUrl, null);}/*** 远程读取文件流* @param netUrl* @param headers* @return*/public static InputStream getFileInputStream(String netUrl, Map<String, String> headers) {InputStream inStream = null;//判断http和httpsif (netUrl.startsWith("https://")) {inStream = getHttpsInputStream(netUrl, headers);} else {inStream = getHttpInputStream(netUrl, headers);}return inStream;}/*** 远程读取文件流(HTTP)* @param netUrl* @param headers* @return*/public static InputStream getHttpInputStream(String netUrl, Map<String, String> headers) {InputStream inStream = null;int statusCode = 408;try {URL url = new URL(netUrl);HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();urlCon.setConnectTimeout(30000);urlCon.setReadTimeout(30000);if (headers != null) {for (String key : headers.keySet()) {urlCon.setRequestProperty(key, headers.get(key));}}statusCode = urlCon.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) {logger.error("远程文件获取错误:{}", netUrl);throw new Exception("文件读取失败");}inStream = urlCon.getInputStream();} catch (Exception e) {logger.error("远程文件获取错误:{}", netUrl);e.printStackTrace();}return inStream;}/*** 远程读取文件流(HTTPS)* @param netUrl* @param headers* @return*/public static InputStream getHttpsInputStream(String netUrl, Map<String, String> headers) {InputStream inStream = null;int statusCode = 408;try {SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");URL url = new URL(netUrl);HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {@Overridepublic boolean verify(String s, SSLSession sslsession) {logger.warn("WARNING: Hostname is not matched for cert.");return true;}};HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());HttpsURLConnection urlCon = (HttpsURLConnection) url.openConnection();urlCon.setConnectTimeout(30000);urlCon.setReadTimeout(30000);if (headers != null) {for (String key : headers.keySet()) {urlCon.setRequestProperty(key, headers.get(key));}}statusCode = urlCon.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) {logger.error("远程文件获取错误:{}", netUrl);throw new Exception("文件读取失败");}inStream = urlCon.getInputStream();} catch (Exception e) {e.printStackTrace();logger.error("远程文件获取错误:{}, 错误描述:{}", netUrl, e.getMessage());}return inStream;}}
相关文章:
一些工具类
1、字符串处理工具类 1.1、StrUtils package com.study.java8.util;/*** Classname:StrUtils* Description:字符串工具类* Date:2023/9/9 9:37* Author:jsz15*/import org.apache.commons.lang.text.StrBuilder; import org.apa…...

20230916后台面经整理
1.面对抢优惠券这样的高负载场景,你从架构、负载均衡等方面说一下你的设计? 答了参考Nginx进行负载均衡,然后在每台服务器怎么怎么弄(架构每一层怎么设计) 参考https://toutiao.io/posts/6z3uu2m/preview,h…...

如何通过快解析测试接口内外网?本地内网ip让外网访问连接
接口调试测试是网络技术员经常工作内容之一。如在公司内部api项目webserver测试,在公司内办公室个人电脑是正常用内网IP访问连接测试的,但在外网电脑需要远程测试时需要怎么测试呢?这里提供一种内网地址让外网访问的通用方法:快解…...

用c++实现五子棋小游戏
五子棋是一款经典小游戏,今天我们就用c实现简单的五子棋小游戏 目录 用到的算法: 思路分析 定义变量 开始写代码 完整代码 结果图: 用到的算法: 合法移动的判断:isValidMove 函数通过检查指定位置是否在棋盘范…...

Android 12.0 SystemUI下拉状态栏定制化之隐藏下拉通知栏布局功能实现(二)
1.前言 在12.0的系统定制化开发中,由于从12.0开始SystemUI下拉状态栏和11.0的变化比较大,所以可以说需要从新分析相关的SystemUI的 布局,然后做分析来实现不同的功能,今天就开始实现关于隐藏SystemUI下拉状态栏中的通知栏布局系列二,去掉下拉状态栏中 通知栏部分 白色的…...

通过finalshell快速在ubuntu上安装jdk1.8
这篇文章主要介绍一下怎么通过finalshell连接ubuntu,然后在ubuntu上安装jdk1.8,让不熟悉linux操作系统的童鞋也能快速地完成安装。 目录 一、准备一台虚拟机 二、安装finalshell远程连接工具 三、获取ubuntu虚拟机的ip地址 四、通过finalshell连接u…...

【Linux从入门到精通】多线程 | 线程互斥(互斥锁)
上篇文章我们对线程 | 线程介绍&线程控制介绍后,本篇文章将会对多线程中的线程互斥与互斥锁的概念进行详解。同时结合实际例子解释了可重入与不被重入函数、临界资源与临界区和原子性的概念。希望本篇文章会对你有所帮助。 文章目录 引入 一、重入与临界 1、1 可…...

Echarts 散点图的详细配置过程
文章目录 散点图 简介配置步骤简易示例 散点图 简介 Echarts散点图是一种常用的数据可视化图表类型,用于展示两个或多个维度的数据分布情况。散点图通过在坐标系中绘制数据点的位置来表示数据的关系。 Echarts散点图的特点如下: 二维数据展示ÿ…...

Nginx详解 五:反向代理
文章目录 1. 正向代理和反向代理1.1 正向代理概述1.1.1 什么是正向代理1.1.2 正向代理的作用1.1.3 正向代理的基本格式 1.2 反向代理概述1.2.1 什么是反向代理1.2.2 反向代理可实现的功能1.2.3 反向代理的可用模块 2. 配置反向代理2.1 反向代理配置参数2.1.1 proxy_pass2.1.2 其…...

【PDF密码】PDF文件打开之后不能打印,怎么解决?
正常的PDF文件是可以打印的,如果PDF文件打开之后发现文件不能打印,我们需要先查看一下自己的打印机是否能够正常运行,如果打印机是正常的,我们再查看一下,文件中的打印功能按钮是否是灰色的状态。 如果PDF中的大多数功…...

深入解析 qsort 函数(下),用冒泡排序模拟实现 qsort 函数
前言:对于库函数有适当了解的朋友们,对于 qsort 函数想必是有认知的,因为他可以对任意数据类型进行排序的功能属实是有点厉害的,本次分享,笔者就给大家带来 qsort 函数的全面的解读 本次知识的分享笔者分为上下俩卷文章…...

Azure + React + ASP.NET Core 项目笔记一:项目环境搭建(二)
有意义的标题 pnpm 安装umi4 脚手架搭建打包语句变更Visual Studio调试Azure 设置变更发布 pnpm 安装 参考官网,或者直接使用npm安装 npm install -g pnpmumi4 脚手架搭建 我这里用的umi4,官网已附上 这里需要把clientapp清空,之后 cd Cl…...

Vmware通过VMware tools设置共享文件夹
步骤说明: 先安装VMware tools,再设置共享文件夹即可。 写在前面: 刚安装虚拟机时,窗口可能显得太小,这是窗口分辨率没有调整导致的。 点击设置->显示->分辨率调整即可 一、安装VMware tools 1.1 点击虚拟机…...
RPA机器人流程自动化专题培训大纲 (针对大学生的版本)
一、课程简介 RPA机器人流程自动化是一种新兴的技术,它通过软件机器人模拟人类操作计算机完成重复性任务,从而实现业务流程的自动化。本课程旨在介绍RPA机器人流程自动化的基本概念、原理和应用,并通过实践案例演示如何应用RPA机器人流程自动…...

数据在内存中的存储——练习4
题目: int main() {char a[1000];int i;for(i0; i<1000; i){a[i] -1-i;}printf("%d",strlen(a));return 0; }思路分析: 已知条件: 通过循环遍历,我们得到的结果是 -1、-2、-3、-4等等。这些是数组内部的存储的元…...

Python 06 之面向对象基础
😀前言 在日常编程和软件开发中,我们通常会遇到各种各样的问题,其中很多问题都可以通过面向对象的程序设计方法来解决。面向对象编程不仅可以使代码更加组织化和系统化,而且还可以提高代码的重用性和可维护性。 . 在本教程中&…...

去除pdf/word的水印艺术字
对于pdf中的水印如果无法去除水印,则先另存为word,然后再按下面办法处理即可: 查看宏,创建:删除艺术字 添加内容: Sub 删除艺术字()Dim sh As ShapeFor Each sh In ActiveDocument.ShapesIf sh.Type msoT…...

【Linux】使用 Alist 实现阿里云盘4K播放
一、安装 Alist 官方文档 默认安装在 /opt/alist 中 curl -fsSL "https://alist.nn.ci/v3.sh" | bash -s install自定义安装路径,将安装路径作为第二个参数添加,必须是绝对路径,如果路径以 alist 结尾,则直接安装到给定…...
Gof23设计模式之状态模式
1.概述 【例】通过按钮来控制一个电梯的状态,一个电梯有开门状态,关门状态,停止状态,运行状态。每一种状态改变,都有可能要根据其他状态来更新处理。例如,如果电梯门现在处于运行时状态,就不能…...

如何免费下载RunWayML产生的视频文件
问题: 首先没有下载的按钮。 其次如果直接“视频另存为”菜单,报错。 解决方案: 1)复制视频链接。 2)新开chrome,在url中粘贴上一步的url路径。 3)当看到视频后,在视频上面右键“…...

JUC笔记(上)-复习 涉及死锁 volatile synchronized CAS 原子操作
一、上下文切换 即使单核CPU也可以进行多线程执行代码,CPU会给每个线程分配CPU时间片来实现这个机制。时间片非常短,所以CPU会不断地切换线程执行,从而让我们感觉多个线程是同时执行的。时间片一般是十几毫秒(ms)。通过时间片分配算法执行。…...

CVE-2020-17519源码分析与漏洞复现(Flink 任意文件读取)
漏洞概览 漏洞名称:Apache Flink REST API 任意文件读取漏洞CVE编号:CVE-2020-17519CVSS评分:7.5影响版本:Apache Flink 1.11.0、1.11.1、1.11.2修复版本:≥ 1.11.3 或 ≥ 1.12.0漏洞类型:路径遍历&#x…...
scikit-learn机器学习
# 同时添加如下代码, 这样每次环境(kernel)启动的时候只要运行下方代码即可: # Also add the following code, # so that every time the environment (kernel) starts, # just run the following code: import sys sys.path.append(/home/aistudio/external-libraries)机…...

MySQL:分区的基本使用
目录 一、什么是分区二、有什么作用三、分类四、创建分区五、删除分区 一、什么是分区 MySQL 分区(Partitioning)是一种将单张表的数据逻辑上拆分成多个物理部分的技术。这些物理部分(分区)可以独立存储、管理和优化,…...

Vue ③-生命周期 || 脚手架
生命周期 思考:什么时候可以发送初始化渲染请求?(越早越好) 什么时候可以开始操作dom?(至少dom得渲染出来) Vue生命周期: 一个Vue实例从 创建 到 销毁 的整个过程。 生命周期四个…...

【Linux】Linux安装并配置RabbitMQ
目录 1. 安装 Erlang 2. 安装 RabbitMQ 2.1.添加 RabbitMQ 仓库 2.2.安装 RabbitMQ 3.配置 3.1.启动和管理服务 4. 访问管理界面 5.安装问题 6.修改密码 7.修改端口 7.1.找到文件 7.2.修改文件 1. 安装 Erlang 由于 RabbitMQ 是用 Erlang 编写的,需要先安…...

Java后端检查空条件查询
通过抛出运行异常:throw new RuntimeException("请输入查询条件!");BranchWarehouseServiceImpl.java // 查询试剂交易(入库/出库)记录Overridepublic List<BranchWarehouseTransactions> queryForReagent(Branch…...

医疗AI模型可解释性编程研究:基于SHAP、LIME与Anchor
1 医疗树模型与可解释人工智能基础 医疗领域的人工智能应用正迅速从理论研究转向临床实践,在这一过程中,模型可解释性已成为确保AI系统被医疗专业人员接受和信任的关键因素。基于树模型的集成算法(如RandomForest、XGBoost、LightGBM)因其卓越的预测性能和相对良好的解释性…...
Python爬虫实战:研究Restkit库相关技术
1. 引言 1.1 研究背景与意义 在当今信息爆炸的时代,互联网上存在着海量的有价值数据。如何高效地采集这些数据并将其应用于实际业务中,成为了许多企业和开发者关注的焦点。网络爬虫技术作为一种自动化的数据采集工具,可以帮助我们从网页中提取所需的信息。而 RESTful API …...

CTF show 数学不及格
拿到题目先查一下壳,看一下信息 发现是一个ELF文件,64位的 用IDA Pro 64 打开这个文件 然后点击F5进行伪代码转换 可以看到有五个if判断,第一个argc ! 5这个判断并没有起太大作用,主要是下面四个if判断 根据题目…...