Java:常用工具类

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

目录

前言

一、IP相关

二、集合操作工具类

三、字符串操作工具类

四、参数传递工具类

五、操作类的工具类

六、操作对象属性的工具类 

七、反射相关的工具类

八、IO相关工具类

九、压缩相关工具类

十、身份证相关工具类

十一、字段验证器

十二、双向查找Map

十三、图片工具类

十四、缓存工具类

十五、加解密工具类

十六、邮件工具类

十七、二维码工具类

十八、日期工具类

总结



前言

工具类可以将复杂的过程包装起来,提供简单的使用,平时开发中必不可少


提示:以下是本篇文章正文内容,下面案例可供参考

一、IP相关

1.1 IpUtil

1.2 InetAddress

例如:获取本机IP

    /**
     * 获取本机IP
     * @return
     */
    private static String getCurrentIP() {
        String ip = "";
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            LOG.error("getLocalHost throws UnknownHostException:", e);
            throw new RuntimeException("can not get ip!");
        }
        if (StringUtils.isBlank(ip)) {
            LOG.error("ip is blank!");
            throw new RuntimeException("ip is blank!");
        }
        return ip;
    }

二、集合操作工具类

2.1 CollectionUtils

public static boolean isEmpty(@Nullable Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

public static boolean isEmpty(@Nullable Map<?, ?> map) {
    return (map == null || map.isEmpty());
}

public static List arrayToList(@Nullable Object source) {
    return Arrays.asList(ObjectUtils.toObjectArray(source));
}

public static boolean contains(@Nullable Iterator<?> iterator, Object element) {
    if (iterator != null) {
        while (iterator.hasNext()) {
            Object candidate = iterator.next();
            if (ObjectUtils.nullSafeEquals(candidate, element)) {
                return true;
            }
        }
    }
    return false;
}

public static <T> T firstElement(@Nullable Set<T> set) {
    if (isEmpty(set)) {
        return null;
    }
    if (set instanceof SortedSet) {
        return ((SortedSet<T>) set).first();
    }

    Iterator<T> it = set.iterator();
    T first = null;
    if (it.hasNext()) {
        first = it.next();
    }
    return first;
}

public static <T> T lastElement(@Nullable Set<T> set) {
    if (isEmpty(set)) {
        return null;
    }
    if (set instanceof SortedSet) {
        return ((SortedSet<T>) set).last();
    }

    // Full iteration necessary...
    Iterator<T> it = set.iterator();
    T last = null;
    while (it.hasNext()) {
        last = it.next();
    }
    return last;
}

2.2 Lists

public static <E> ArrayList<E> newArrayList() {
    return new ArrayList();
}

public static <E> ArrayList<E> newArrayList(E... elements) {
    Preconditions.checkNotNull(elements);
    int capacity = computeArrayListCapacity(elements.length);
    ArrayList<E> list = new ArrayList(capacity);
    Collections.addAll(list, elements);
    return list;
}

public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
    return new CopyOnWriteArrayList();
}

三、字符串操作工具类

3.1 StringUtils

public static boolean isEmpty(CharSequence cs) {
    return cs == null || cs.length() == 0;
}

public static boolean isNotEmpty(CharSequence cs) {
    return !isEmpty(cs);
}

public static boolean isBlank(CharSequence cs) {
    int strLen;
    if (cs != null && (strLen = cs.length()) != 0) {
        for(int i = 0; i < strLen; ++i) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }

        return true;
    } else {
        return true;
    }
}

public static boolean isNotBlank(CharSequence cs) {
    return !isBlank(cs);
}

public static String trim(String str) {
    return str == null ? null : str.trim();
}

public static int compare(String str1, String str2) {
    return compare(str1, str2, true);
}

public static int compare(String str1, String str2, boolean nullIsLess) {
    if (str1 == str2) {
        return 0;
    } else if (str1 == null) {
        return nullIsLess ? -1 : 1;
    } else if (str2 == null) {
        return nullIsLess ? 1 : -1;
    } else {
        return str1.compareTo(str2);
    }
}

public static int indexOf(CharSequence seq, int searchChar) {
    return isEmpty(seq) ? -1 : CharSequenceUtils.indexOf(seq, searchChar, 0);
}

public static int indexOf(CharSequence seq, int searchChar, int startPos) {
    return isEmpty(seq) ? -1 : CharSequenceUtils.indexOf(seq, searchChar, startPos);
}

public static boolean contains(CharSequence seq, CharSequence searchSeq) {
    if (seq != null && searchSeq != null) {
        return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0;
    } else {
        return false;
    }
}

四、参数传递工具类

4.1 MdcUtil 

五、操作类的工具类

5.1 ClassUtils

public static boolean hasMethod(Class<?> clazz, Method method) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(method, "Method must not be null");
    if (clazz == method.getDeclaringClass()) {
        return true;
    }
    String methodName = method.getName();
    Class<?>[] paramTypes = method.getParameterTypes();
    return getMethodOrNull(clazz, methodName, paramTypes) != null;
}

public static boolean hasMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    return (getMethodIfAvailable(clazz, methodName, paramTypes) != null);
}

public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(methodName, "Method name must not be null");
    try {
        Method method = clazz.getMethod(methodName, args);
        return Modifier.isStatic(method.getModifiers()) ? method : null;
    }
    catch (NoSuchMethodException ex) {
        return null;
    }
}

public static Class<?> forName(String name, @Nullable ClassLoader classLoader)
        throws ClassNotFoundException, LinkageError {

    Assert.notNull(name, "Name must not be null");

    Class<?> clazz = resolvePrimitiveClassName(name);
    if (clazz == null) {
        clazz = commonClassCache.get(name);
    }
    if (clazz != null) {
        return clazz;
    }

    // "java.lang.String[]" style arrays
    if (name.endsWith(ARRAY_SUFFIX)) {
        String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
        Class<?> elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[Ljava.lang.String;" style arrays
    if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
        String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[[I" or "[[Ljava.lang.String;" style arrays
    if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
        String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader clToUse = classLoader;
    if (clToUse == null) {
        clToUse = getDefaultClassLoader();
    }
    try {
        return Class.forName(name, false, clToUse);
    }
    catch (ClassNotFoundException ex) {
        int lastDotIndex = name.lastIndexOf(PACKAGE_SEPARATOR);
        if (lastDotIndex != -1) {
            String innerClassName =
                    name.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR + name.substring(lastDotIndex + 1);
            try {
                return Class.forName(innerClassName, false, clToUse);
            }
            catch (ClassNotFoundException ex2) {
                // Swallow - let original exception get through
            }
        }
        throw ex;
    }
}

六、操作对象属性的工具类 

6.1 BeanUtils

public static void copyProperties(Object source, Object target) throws BeansException {
    copyProperties(source, target, null, (String[]) null);
}

public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
    copyProperties(source, target, null, ignoreProperties);
}

private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
        @Nullable String... ignoreProperties) throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                    "] not assignable to Editable class [" + editable.getName() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null &&
                        ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    }
                    catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                    }
                }
            }
        }
    }
}

6.2 Objects

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}

public static boolean deepEquals(Object a, Object b) {
    if (a == b)
        return true;
    else if (a == null || b == null)
        return false;
    else
        return Arrays.deepEquals0(a, b);
}

public static <T> int compare(T a, T b, Comparator<? super T> c) {
    return (a == b) ? 0 :  c.compare(a, b);
}

public static boolean isNull(Object obj) {
    return obj == null;
}

public static boolean nonNull(Object obj) {
    return obj != null;
}

七、反射相关的工具类

7.1 ReflectionUtils

public static void makeAccessible(Constructor<?> ctor) {
    if ((!Modifier.isPublic(ctor.getModifiers()) ||
            !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
        ctor.setAccessible(true);
    }
}

public static Method findMethod(Class<?> clazz, String name) {
    return findMethod(clazz, name, EMPTY_CLASS_ARRAY);
}

public static Method findMethod(Class<?> clazz, String name, @Nullable Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (searchType != null) {
        Method[] methods = (searchType.isInterface() ? searchType.getMethods() :
                getDeclaredMethods(searchType, false));
        for (Method method : methods) {
            if (name.equals(method.getName()) && (paramTypes == null || hasSameParams(method, paramTypes))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

public static Object invokeMethod(Method method, @Nullable Object target) {
    return invokeMethod(method, target, EMPTY_OBJECT_ARRAY);
}

public static Object invokeMethod(Method method, @Nullable Object target, @Nullable Object... args) {
    try {
        return method.invoke(target, args);
    }
    catch (Exception ex) {
        handleReflectionException(ex);
    }
    throw new IllegalStateException("Should never get here");
}

public static Method[] getAllDeclaredMethods(Class<?> leafClass) {
    final List<Method> methods = new ArrayList<>(32);
    doWithMethods(leafClass, methods::add);
    return methods.toArray(EMPTY_METHOD_ARRAY);
}

public static void makeAccessible(Method method) {
    if ((!Modifier.isPublic(method.getModifiers()) ||
            !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
        method.setAccessible(true);
    }
}

private static Field[] getDeclaredFields(Class<?> clazz) {
    Assert.notNull(clazz, "Class must not be null");
    Field[] result = declaredFieldsCache.get(clazz);
    if (result == null) {
        try {
            result = clazz.getDeclaredFields();
            declaredFieldsCache.put(clazz, (result.length == 0 ? EMPTY_FIELD_ARRAY : result));
        }
        catch (Throwable ex) {
            throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() +
                    "] from ClassLoader [" + clazz.getClassLoader() + "]", ex);
        }
    }
    return result;
}

7.2 ReflectUtil(Hutool)

public static boolean hasField(Class<?> beanClass, String name) throws SecurityException {
    return null != getField(beanClass, name);
}

public static String getFieldName(Field field) {
    if (null == field) {
        return null;
    } else {
        Alias alias = (Alias)field.getAnnotation(Alias.class);
        return null != alias ? alias.value() : field.getName();
    }
}

public static Field getField(Class<?> beanClass, String name) throws SecurityException {
    Field[] fields = getFields(beanClass);
    return (Field)ArrayUtil.firstMatch((field) -> {
        return name.equals(getFieldName(field));
    }, fields);
}

public static Object[] getFieldsValue(Object obj) {
    if (null != obj) {
        Field[] fields = getFields(obj instanceof Class ? (Class)obj : obj.getClass());
        if (null != fields) {
            Object[] values = new Object[fields.length];

            for(int i = 0; i < fields.length; ++i) {
                values[i] = getFieldValue(obj, fields[i]);
            }

            return values;
        }
    }

    return null;
}

public static Method[] getPublicMethods(Class<?> clazz) {
    return null == clazz ? null : clazz.getMethods();
}

public static List<Method> getPublicMethods(Class<?> clazz, Filter<Method> filter) {
    if (null == clazz) {
        return null;
    } else {
        Method[] methods = getPublicMethods(clazz);
        ArrayList methodList;
        if (null != filter) {
            methodList = new ArrayList();
            Method[] var4 = methods;
            int var5 = methods.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Method method = var4[var6];
                if (filter.accept(method)) {
                    methodList.add(method);
                }
            }
        } else {
            methodList = CollUtil.newArrayList(methods);
        }

        return methodList;
    }
}

public static Method getMethod(Class<?> clazz, boolean ignoreCase, String methodName, Class<?>... paramTypes) throws SecurityException {
    if (null != clazz && !StrUtil.isBlank(methodName)) {
        Method[] methods = getMethods(clazz);
        if (ArrayUtil.isNotEmpty(methods)) {
            Method[] var5 = methods;
            int var6 = methods.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                Method method = var5[var7];
                if (StrUtil.equals(methodName, method.getName(), ignoreCase) && ClassUtil.isAllAssignableFrom(method.getParameterTypes(), paramTypes) && !method.isBridge()) {
                    return method;
                }
            }
        }

        return null;
    } else {
        return null;
    }
}

八、IO相关工具类

8.1 IoUtil(流操作)(Hutool)

public static BufferedReader getReader(InputStream in, Charset charset) {
    if (null == in) {
        return null;
    } else {
        InputStreamReader reader;
        if (null == charset) {
            reader = new InputStreamReader(in);
        } else {
            reader = new InputStreamReader(in, charset);
        }

        return new BufferedReader(reader);
    }
}

public static BufferedReader getReader(Reader reader) {
    if (null == reader) {
        return null;
    } else {
        return reader instanceof BufferedReader ? (BufferedReader)reader : new BufferedReader(reader);
    }
}

public static OutputStreamWriter getWriter(OutputStream out, Charset charset) {
    if (null == out) {
        return null;
    } else {
        return null == charset ? new OutputStreamWriter(out) : new OutputStreamWriter(out, charset);
    }
}

public static String read(InputStream in, Charset charset) throws IORuntimeException {
    return StrUtil.str(readBytes(in), charset);
}

public static <T> T readObj(InputStream in) throws IORuntimeException, UtilException {
    return readObj((InputStream)in, (Class)null);
}

public static <T> T readObj(InputStream in, Class<T> clazz) throws IORuntimeException, UtilException {
    try {
        return readObj(in instanceof ValidateObjectInputStream ? (ValidateObjectInputStream)in : new ValidateObjectInputStream(in, new Class[0]), clazz);
    } catch (IOException var3) {
        throw new IORuntimeException(var3);
    }
}

public static ByteArrayInputStream toStream(String content, Charset charset) {
    return content == null ? null : toStream(StrUtil.bytes(content, charset));
}

public static ByteArrayInputStream toUtf8Stream(String content) {
    return toStream(content, CharsetUtil.CHARSET_UTF_8);
}

public static FileInputStream toStream(File file) {
    try {
        return new FileInputStream(file);
    } catch (FileNotFoundException var2) {
        throw new IORuntimeException(var2);
    }
}

public static ByteArrayInputStream toStream(byte[] content) {
    return content == null ? null : new ByteArrayInputStream(content);
}

public static void write(OutputStream out, boolean isCloseOut, byte[] content) throws IORuntimeException {
    try {
        out.write(content);
    } catch (IOException var7) {
        throw new IORuntimeException(var7);
    } finally {
        if (isCloseOut) {
            close(out);
        }

    }

}

public static void flush(Flushable flushable) {
    if (null != flushable) {
        try {
            flushable.flush();
        } catch (Exception var2) {
        }
    }

}

public static void close(Closeable closeable) {
    if (null != closeable) {
        try {
            closeable.close();
        } catch (Exception var2) {
        }
    }

}

8.2 FileUtil(文件读写操作)(Hutool)

public static boolean isEmpty(File file) {
    if (null != file && file.exists()) {
        if (file.isDirectory()) {
            String[] subFiles = file.list();
            return ArrayUtil.isEmpty(subFiles);
        } else if (file.isFile()) {
            return file.length() <= 0L;
        } else {
            return false;
        }
    } else {
        return true;
    }
}

public static File newFile(String path) {
    return new File(path);
}

public static File file(String path) {
    return null == path ? null : new File(getAbsolutePath(path));
}

public static File file(URI uri) {
    if (uri == null) {
        throw new NullPointerException("File uri is null!");
    } else {
        return new File(uri);
    }
}

public static String getUserHomePath() {
    return System.getProperty("user.home");
}

public static boolean exist(String path) {
    return null != path && file(path).exists();
}

public static boolean exist(File file) {
    return null != file && file.exists();
}

public static long size(File file, boolean includeDirSize) {
    if (null != file && file.exists() && !isSymlink(file)) {
        if (!file.isDirectory()) {
            return file.length();
        } else {
            long size = includeDirSize ? file.length() : 0L;
            File[] subFiles = file.listFiles();
            if (ArrayUtil.isEmpty(subFiles)) {
                return 0L;
            } else {
                File[] var5 = subFiles;
                int var6 = subFiles.length;

                for(int var7 = 0; var7 < var6; ++var7) {
                    File subFile = var5[var7];
                    size += size(subFile, includeDirSize);
                }

                return size;
            }
        }
    } else {
        return 0L;
    }
}

public static File mkdir(String dirPath) {
    if (dirPath == null) {
        return null;
    } else {
        File dir = file(dirPath);
        return mkdir(dir);
    }
}

public static File mkdir(File dir) {
    if (dir == null) {
        return null;
    } else {
        if (!dir.exists()) {
            mkdirsSafely(dir, 5, 1L);
        }

        return dir;
    }
}

public static boolean del(File file) throws IORuntimeException {
    if (file != null && file.exists()) {
        if (file.isDirectory()) {
            boolean isOk = clean(file);
            if (!isOk) {
                return false;
            }
        }

        Path path = file.toPath();

        try {
            delFile(path);
        } catch (DirectoryNotEmptyException var3) {
            del((Path)path);
        } catch (IOException var4) {
            throw new IORuntimeException(var4);
        }

        return true;
    } else {
        return true;
    }
}

public static File rename(File file, String newName, boolean isRetainExt, boolean isOverride) {
    if (isRetainExt) {
        String extName = extName(file);
        if (StrUtil.isNotBlank(extName)) {
            newName = newName.concat(".").concat(extName);
        }
    }

    return rename(file.toPath(), newName, isOverride).toFile();
}

8.3 FileTypeUtil(文件类型判断)(Hutool)

public static String getType(InputStream in, String filename) {
    String typeName = getType(in);
    if (null == typeName) {
        typeName = FileUtil.extName(filename);
    } else {
        String extName;
        if ("xls".equals(typeName)) {
            extName = FileUtil.extName(filename);
            if ("doc".equalsIgnoreCase(extName)) {
                typeName = "doc";
            } else if ("msi".equalsIgnoreCase(extName)) {
                typeName = "msi";
            }
        } else if ("zip".equals(typeName)) {
            extName = FileUtil.extName(filename);
            if ("docx".equalsIgnoreCase(extName)) {
                typeName = "docx";
            } else if ("xlsx".equalsIgnoreCase(extName)) {
                typeName = "xlsx";
            } else if ("pptx".equalsIgnoreCase(extName)) {
                typeName = "pptx";
            } else if ("jar".equalsIgnoreCase(extName)) {
                typeName = "jar";
            } else if ("war".equalsIgnoreCase(extName)) {
                typeName = "war";
            } else if ("ofd".equalsIgnoreCase(extName)) {
                typeName = "ofd";
            }
        } else if ("jar".equals(typeName)) {
            extName = FileUtil.extName(filename);
            if ("xlsx".equalsIgnoreCase(extName)) {
                typeName = "xlsx";
            } else if ("docx".equalsIgnoreCase(extName)) {
                typeName = "docx";
            } else if ("pptx".equalsIgnoreCase(extName)) {
                typeName = "pptx";
            }
        }
    }

    return typeName;
}

public static String getType(File file) throws IORuntimeException {
    FileInputStream in = null;

    String var2;
    try {
        in = IoUtil.toStream(file);
        var2 = getType(in, file.getName());
    } finally {
        IoUtil.close(in);
    }

    return var2;
}

九、压缩相关工具类

9.1 ZipUtil(Hutool)

public static ZipFile toZipFile(File file, Charset charset) {
    try {
        return new ZipFile(file, (Charset)ObjectUtil.defaultIfNull(charset, CharsetUtil.CHARSET_UTF_8));
    } catch (IOException var3) {
        throw new IORuntimeException(var3);
    }
}

public static byte[] gzip(InputStream in) throws UtilException {
    return gzip(in, 32);
}

public static byte[] gzip(InputStream in, int length) throws UtilException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
    Gzip.of(in, bos).gzip().close();
    return bos.toByteArray();
}

public static String unGzip(byte[] buf, String charset) throws UtilException {
    return StrUtil.str(unGzip(buf), charset);
}

public static byte[] unGzip(byte[] buf) throws UtilException {
    return unGzip(new ByteArrayInputStream(buf), buf.length);
}

public static byte[] unGzip(InputStream in) throws UtilException {
    return unGzip(in, 32);
}

public static byte[] unGzip(InputStream in, int length) throws UtilException {
    FastByteArrayOutputStream bos = new FastByteArrayOutputStream(length);
    Gzip.of(in, bos).unGzip().close();
    return bos.toByteArray();
}

十、身份证相关工具类

10.1 IdcardUtil(Hutool)

public static boolean isValidCard(String idCard) {
    if (StrUtil.isBlank(idCard)) {
        return false;
    } else {
        int length = idCard.length();
        switch(length) {
        case 10:
            String[] cardVal = isValidCard10(idCard);
            return null != cardVal && "true".equals(cardVal[2]);
        case 15:
            return isValidCard15(idCard);
        case 18:
            return isValidCard18(idCard);
        default:
            return false;
        }
    }
}

public static boolean isValidCard18(String idcard) {
    return isValidCard18(idcard, true);
}

public static boolean isValidCard18(String idcard, boolean ignoreCase) {
    if (18 != idcard.length()) {
        return false;
    } else {
        String proCode = idcard.substring(0, 2);
        if (null == CITY_CODES.get(proCode)) {
            return false;
        } else if (!Validator.isBirthday(idcard.substring(6, 14))) {
            return false;
        } else {
            String code17 = idcard.substring(0, 17);
            if (ReUtil.isMatch(PatternPool.NUMBERS, code17)) {
                char val = getCheckCode18(code17);
                return CharUtil.equals(val, idcard.charAt(17), ignoreCase);
            } else {
                return false;
            }
        }
    }
}

public static String getBirth(String idCard) {
    Assert.notBlank(idCard, "id card must be not blank!", new Object[0]);
    int len = idCard.length();
    if (len < 15) {
        return null;
    } else {
        if (len == 15) {
            idCard = convert15To18(idCard);
        }

        return ((String)Objects.requireNonNull(idCard)).substring(6, 14);
    }
}

public static DateTime getBirthDate(String idCard) {
    String birthByIdCard = getBirthByIdCard(idCard);
    return null == birthByIdCard ? null : DateUtil.parse(birthByIdCard, DatePattern.PURE_DATE_FORMAT);
}

public static int getAgeByIdCard(String idcard) {
    return getAgeByIdCard(idcard, DateUtil.date());
}

public static String getProvinceByIdCard(String idcard) {
    String code = getProvinceCodeByIdCard(idcard);
    return StrUtil.isNotBlank(code) ? (String)CITY_CODES.get(code) : null;
}

public static String getCityCodeByIdCard(String idcard) {
    int len = idcard.length();
    return len != 15 && len != 18 ? null : idcard.substring(0, 4);
}

十一、字段验证器

11.1 Validator(Hutool)

public static <T> T validateNull(T value, String errorMsgTemplate, Object... params) throws ValidateException {
    if (isNotNull(value)) {
        throw new ValidateException(errorMsgTemplate, params);
    } else {
        return null;
    }
}

public static <T> T validateNotNull(T value, String errorMsgTemplate, Object... params) throws ValidateException {
    if (isNull(value)) {
        throw new ValidateException(errorMsgTemplate, params);
    } else {
        return value;
    }
}

public static boolean isEmpty(Object value) {
    return null == value || value instanceof String && StrUtil.isEmpty((String)value);
}

public static boolean isNotEmpty(Object value) {
    return !isEmpty(value);
}

public static boolean equal(Object t1, Object t2) {
    return ObjectUtil.equal(t1, t2);
}

public static boolean isMatchRegex(Pattern pattern, CharSequence value) {
    return ReUtil.isMatch(pattern, value);
}

public static boolean isMatchRegex(String regex, CharSequence value) {
    return ReUtil.isMatch(regex, value);
}

public static boolean isNumber(CharSequence value) {
    return NumberUtil.isNumber(value);
}

public static boolean hasNumber(CharSequence value) {
    return ReUtil.contains(PatternPool.NUMBERS, value);
}

public static boolean isWord(CharSequence value) {
    return isMatchRegex(PatternPool.WORD, value);
}

public static boolean isMoney(CharSequence value) {
    return isMatchRegex(MONEY, value);
}

public static boolean isEmail(CharSequence value) {
    return isMatchRegex(EMAIL, value);
}

public static boolean isMobile(CharSequence value) {
    return isMatchRegex(MOBILE, value);
}

public static boolean isIpv4(CharSequence value) {
    return isMatchRegex(IPV4, value);
}

public static boolean isIpv6(CharSequence value) {
    return isMatchRegex(IPV6, value);
}

public static boolean isUrl(CharSequence value) {
    if (StrUtil.isBlank(value)) {
        return false;
    } else {
        try {
            new URL(StrUtil.str(value));
            return true;
        } catch (MalformedURLException var2) {
            return false;
        }
    }
}

十二、双向查找Map

12.1 BiMap(Hutool)

public BiMap(Map<K, V> raw) {
    super(raw);
}

public V put(K key, V value) {
    if (null != this.inverse) {
        this.inverse.put(value, key);
    }

    return super.put(key, value);
}

public void putAll(Map<? extends K, ? extends V> m) {
    super.putAll(m);
    if (null != this.inverse) {
        m.forEach((key, value) -> {
            this.inverse.put(value, key);
        });
    }

}

public V remove(Object key) {
    V v = super.remove(key);
    if (null != this.inverse && null != v) {
        this.inverse.remove(v);
    }

    return v;
}

public boolean remove(Object key, Object value) {
    return super.remove(key, value) && null != this.inverse && this.inverse.remove(value, key);
}

public void clear() {
    super.clear();
    this.inverse = null;
}

public Map<V, K> getInverse() {
    if (null == this.inverse) {
        this.inverse = MapUtil.inverse(this.getRaw());
    }

    return this.inverse;
}

public K getKey(V value) {
    return this.getInverse().get(value);
}

十三、图片工具类

13.1 ImgUtil(Hutool)

public static void compress(File imageFile, File outFile, float quality) throws IORuntimeException {
    Img.from(imageFile).setQuality(quality).write(outFile);
}

public static BufferedImage toImage(String base64) throws IORuntimeException {
    return toImage(Base64.decode(base64));
}

public static BufferedImage toImage(byte[] imageBytes) throws IORuntimeException {
    return read((InputStream)(new ByteArrayInputStream(imageBytes)));
}

public static ByteArrayInputStream toStream(Image image, String imageType) {
    return IoUtil.toStream(toBytes(image, imageType));
}

public static void writeJpg(Image image, ImageOutputStream destImageStream) throws IORuntimeException {
    write(image, "jpg", destImageStream);
}

public static void writePng(Image image, ImageOutputStream destImageStream) throws IORuntimeException {
    write(image, "png", destImageStream);
}

public static void writeJpg(Image image, OutputStream out) throws IORuntimeException {
    write(image, "jpg", out);
}

public static void writePng(Image image, OutputStream out) throws IORuntimeException {
    write(image, "png", out);
}

public static void write(ImageInputStream srcStream, String formatName, ImageOutputStream destStream) {
    write((Image)read(srcStream), formatName, (ImageOutputStream)destStream);
}

十四、缓存工具类

14.1 CacheUtil(Hutool)

public static <K, V> FIFOCache<K, V> newFIFOCache(int capacity) {
    return new FIFOCache(capacity);
}

public static <K, V> LFUCache<K, V> newLFUCache(int capacity) {
    return new LFUCache(capacity);
}

十五、加解密工具类

SymmetricCrypto(对称加密)(Hutool)

AsymmetricCrypto(非对称加密)(Hutool)

Digester(摘要加密)(Hutool)

十六、邮件工具类

MailUtil(Hutool)

十七、二维码工具类

17.1 QrCodeUtil(Hutool)

public static BitMatrix encode(String content, int width, int height) {
    return encode(content, BarcodeFormat.QR_CODE, width, height);
}

public static BitMatrix encode(String content, QrConfig config) {
    return encode(content, BarcodeFormat.QR_CODE, config);
}

public static BitMatrix encode(String content, BarcodeFormat format, int width, int height) {
    return encode(content, format, new QrConfig(width, height));
}

public static BitMatrix encode(String content, BarcodeFormat format, QrConfig config) {
    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    if (null == config) {
        config = new QrConfig();
    }

    try {
        BitMatrix bitMatrix = multiFormatWriter.encode(content, format, config.width, config.height, config.toHints(format));
        return bitMatrix;
    } catch (WriterException var6) {
        throw new QrCodeException(var6);
    }
}

public static String decode(InputStream qrCodeInputstream) {
    return decode((Image)ImgUtil.read(qrCodeInputstream));
}

public static String decode(File qrCodeFile) {
    return decode((Image)ImgUtil.read(qrCodeFile));
}

public static String decode(Image image) {
    return decode(image, true, false);
}

public static String decode(Image image, boolean isTryHarder, boolean isPureBarcode) {
    return decode(image, buildHints(isTryHarder, isPureBarcode));
}

public static String decode(Image image, Map<DecodeHintType, Object> hints) {
    MultiFormatReader formatReader = new MultiFormatReader();
    formatReader.setHints(hints);
    LuminanceSource source = new BufferedImageLuminanceSource(ImgUtil.toBufferedImage(image));
    Result result = _decode(formatReader, new HybridBinarizer(source));
    if (null == result) {
        result = _decode(formatReader, new GlobalHistogramBinarizer(source));
    }

    return null != result ? result.getText() : null;
}

public static byte[] generatePng(String content, int width, int height) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    generate(content, width, height, "png", out);
    return out.toByteArray();
}

public static byte[] generatePng(String content, QrConfig config) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    generate(content, config, "png", out);
    return out.toByteArray();
}

十八、日期工具类

DateUtil(Hutool)


总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值