IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Java常用的工具类 -> 正文阅读

[Java知识库]Java常用的工具类

IOUtils

IOUtils: Apache Commons IO用来处理输入-输出流
详情介绍: https://blog.csdn.net/l2580258/article/details/89227761
添加的依赖:

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
</dependency>

引入的包:

import org.apache.commons.io.IOUtils;

IOUtils 提供的一些常见的方法:

closeQuietly : 它将无条件的关闭一个可被关闭的对象而不抛出任何异常
copy: 这个方法将内容按字节从一个InputStream对象复制到一个OutputStream对象,并返回复制的字节数。同样有一个方法支持从Reader对象复制到Writer对象
IOUtils.toInputStream(A ,“utf-8”): 创建一个InputStream

FileUtils

FileUtils是 commons-io包下的FileUtils
详情介绍: 连接

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>
import org.apache.commons.io.FileUtils;

提供了以下的方法:

1、copyFile(File srcFile, File destFile):拷贝文件夹
2、copyDirectory(File srcDir, File destDir):拷贝目录及文件
3、deleteQuietly(File file): 删除指定文件,从不引发异常
4、deleteDirectory(File directory)递归删除目录
5、cleanDirectory(File directory):清空目录

StringUtils

StringUtils类在操作字符串是安全的,不会报空指针异常,也正因此,在操作字符串时使用StringUtils相比使用原生的String会更加安全。
详情介绍:https://blog.csdn.net/sailor125/article/details/90765202
依赖

org.apache.commons commons-lang3 3.3.2 import org.apache.commons.lang3.StringUtils;
StringUtils提供的一些常见方法
1.判断字符串是否为空: isEmpty(isNotEmpty)和 isBlank(isNotBlank)
isBlank:判断更严谨,包含的有空串("")、空白符(空格""," “,制表符”\t",回车符"\r","\n"等)以及null值;
isEmpty:包含是空串("")和null值,不包含空白符;
2. 移除单个字符: StringUtils.remove(String str, String remove);
3.删除所有空白符: deleteWhitespace(String str)
4. 比较两个字符串:StringUtils.equals("", “”); //可以进行空置null
StringUtils.equalsIgnoreCase(“ss”, “Ss”); //不区分大小写–结果是true

DateUtils

DateUtils提供了一些常用的时间相关的格式转换操作

/**
* 提供时间先关的常用方法
*/

public class DateUtils {


    //当前时间
    public static Date DATE_NOW=new Date();


    /**
     * 得到完整的时间戳,格式:yyyyMMddHHmmssSSS(年月日时分秒毫秒)
     * @return 完整的时间戳
     */
    public static String getFullTimeStamp(){
        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) ;
    }


    /**
     * 得到简单的时间戳,格式:yyyyMMdd(年月日)
     * @return 简单的时间戳
     */
    public static String getSimpleTimeStamp(){
        return new SimpleDateFormat("yyyyMMdd").format(new Date()) ;
    }


    /**
     * 根据指定的格式得到时间戳
     * @param pattern 指定的格式
     * @return 指定格式的时间戳
     */
    public static String getTimeStampByPattern(String pattern){
        return new SimpleDateFormat(pattern).format(new Date()) ;
    }


    /**
     * 得到当前日期格式化后的字符串,格式:yyyy-MM-dd(年-月-日)
     * @return 当前日期格式化后的字符串
     */
    public static String getTodayStr(){
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date()) ;
    }


    /**
     * 时间戳,格式:yyyy-MM-dd HH:mm:ss(年-月-日 时:分:秒)
     * @return 简单的时间戳
     */
    public static String getDateTimeStamp(Date date){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) ;
    }


    public static Date getDateByString(String str){
        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date dateTime = null;
        try {
            dateTime = sim.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateTime;
    }
}

JacksonUtils

通过jackson工具我们可以封装一些常用的方法。
依赖:

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.3</version>
</dependency>

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
   <version>2.9.3</version>
</dependency>

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-annotations</artifactId>
   <version>2.9.3</version>
</dependency>

JacksonUtils

/**
* Json工具类,基于Jackson实现
*
*
*/
public class JacksonUtils {
    /**
     * 将对象转化成json
     *
     * @param t
     * @return
     * @throws JsonProcessingException
     */
    public static <T> String toJson(T t) throws JsonProcessingException {
        return OBJECT_MAPPER.get().writeValueAsString(t);
    }

    /**
     * 将json转化成bean
     *
     * @param json
     * @param valueType
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static <T> T toEntity(String json, Class<T> valueType)
            throws JsonParseException, JsonMappingException, IOException {
        return OBJECT_MAPPER.get().readValue(json, valueType);
    }


    /**
     * 将json转化成List
     *
     * @param json
     * @param collectionClass
     * @param elementClass
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static <T> List<T> toList(String json, Class<? extends List> collectionClass, Class<T> elementClass)
            throws JsonParseException, JsonMappingException, IOException {
        JavaType javaType = OBJECT_MAPPER.get().getTypeFactory().constructCollectionType(collectionClass, elementClass);
        return OBJECT_MAPPER.get().readValue(json, javaType);
    }


    /**
     * 将json转化成Map
     *
     * @param json
     * @param mapClass
     * @param keyClass
     * @param valueClass
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static <K, V> Map<K, V> toMap(String json, Class<? extends Map> mapClass, Class<K> keyClass,
                                         Class<V> valueClass) throws JsonParseException, JsonMappingException, IOException {
        JavaType javaType = OBJECT_MAPPER.get().getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
        return OBJECT_MAPPER.get().readValue(json, javaType);
    }


    // ################################################################################################################


    /**
     * 禁止调用无参构造
     *
     * @throws IllegalAccessException
     */
    private JacksonUtils() throws IllegalAccessException {
        throw new IllegalAccessException("Can't create an instance!");
    }


    /**
     * 使用ThreadLocal创建对象,防止出现线程安全问题
     */
    private static final ThreadLocal<ObjectMapper> OBJECT_MAPPER = new ThreadLocal<ObjectMapper>() {
        @Override
        protected ObjectMapper initialValue() {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略不存在的字段
            return objectMapper;
        }
    };
}

HttpUtil

HttpUtil提供了模拟post、get请求,实现跨系统的数据访问。
HttpConnectionManager: 提供http连接管理
HttpUtil :提供具体的请求方法

HttpConnectionManager

public class HttpConnectionManager {


    private static final Logger logger = LoggerFactory.getLogger(HttpConnectionManager.class);
    /**
     * 最大连接数增加
     */
    private static final int MAX_CONNECTION_SIZE = 200;
    /**
     * 每个路由基础的连接数
     */
    private static final int MAX_PER_ROUTE = 50;


    private PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;


    private HttpConnectionManager(boolean isTrust) {
        try {
            SSLContext sslContext;
            if(isTrust) {
                sslContext = getSSLContextTrustAll();
            } else {
                sslContext = getSSLContextCertificate();
            }
            init(sslContext);
        } catch (Exception e) {
            logger.error("初始化http连接池失败: ", e);
        }
    }


    private static final class HttpConnectionManagerHolder {
        private static HttpConnectionManager httpConnectionManager = new HttpConnectionManager(true);
    }


    private static final class HttpsConnectionManagerHolder {
        private static HttpConnectionManager httpConnectionManager = new HttpConnectionManager(false);
    }

    public static HttpConnectionManager getHttpClientFactory() {
        return HttpConnectionManagerHolder.httpConnectionManager;
    }


    public static HttpConnectionManager getHttpsClientFactory() {
        return HttpsConnectionManagerHolder.httpConnectionManager;
    }


    private void init(SSLContext sslContext) {
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", new PlainConnectionSocketFactory())
                .build();
        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        poolingHttpClientConnectionManager.setMaxTotal(MAX_CONNECTION_SIZE);
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
    }


    CloseableHttpClient getHttpClient() {
        return HttpClients.custom()
                .setConnectionManager(poolingHttpClientConnectionManager)
                .setKeepAliveStrategy(connectionKeepAliveStrategy)
                .build();
    }


    private SSLContext getSSLContextCertificate() throws Exception {
        // 获得密匙库
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream inputStream = new FileInputStream(
                new File("D:\\idea_workspace\\learning\\src\\main\\resources\\https\\keystore.p12"))) {
            // 密匙库的密码
            trustStore.load(inputStream, "iflytek".toCharArray());
        }
        return SSLContexts.custom().loadTrustMaterial(trustStore, TrustSelfSignedStrategy.INSTANCE)
                .build();
    }

    private SSLContext getSSLContextTrustAll() throws Exception {
        // 信任所有
        return new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
    }

    /**
     * DefaultConnectionKeepAliveStrategy 默认实现
     */
    private ConnectionKeepAliveStrategy connectionKeepAliveStrategy = (response, context) -> {
        final HeaderElementIterator it = new BasicHeaderElementIterator(
                response.headerIterator(HTTP.CONN_KEEP_ALIVE));
        while (it.hasNext()) {
            final HeaderElement headerElement = it.nextElement();
            final String param = headerElement.getName();
            final String value = headerElement.getValue();
            if (value != null && "timeout".equalsIgnoreCase(param)) {
                try {
                    return Long.parseLong(value) * 1000;
                } catch (final NumberFormatException ignore) {
                    return 1;
                }
            }
        }
        return 1;
    };
}

HttpUtil

请求体可以结合jaskson来实现:

public class HttpUtil {
    private HttpUtil() {
    }
    private static final String ENCODING = "UTF-8";
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String get(String url, Map<String, String> params) {
        String content = "";
        CloseableHttpClient httpClient = HttpConnectionManager.getHttpClientFactory().getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            httpGet.addHeader(entry.getKey(), entry.getValue());
        }
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            return parseResult(response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return content;
    }


    public void SubmitPost(String url,String filename1,String filename2, String filepath){
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpPost = new HttpPost(url);
            EntityBuilder entityBuilder = EntityBuilder.create();
            entityBuilder.setParameters(new BasicNameValuePair("test", "test"));
            HttpEntity httpEntity = entityBuilder.build();
            httpPost.setEntity(httpEntity);
            HttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == HttpStatus.SC_OK){
                System.out.println("服务器正常响应.....");
                HttpEntity resEntity = response.getEntity();
                System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据
                EntityUtils.consume(resEntity);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {
            }
        }
    }

    public static String post(String url, InputStream inputStream) {
        return post(url, null, new InputStreamEntity(inputStream));
    }

    public static String post(String url, Map<String, String> head, List<NameValuePair> pairList) throws UnsupportedEncodingException {
        UrlEncodedFormEntity basicHttpEntity = new UrlEncodedFormEntity(pairList, "UTF-8");
        basicHttpEntity.setContentType("application/x-www-form-urlencoded");
        return post(url, null, basicHttpEntity);
    }

    public static String post(String url, Map<String, String> heads, String body) {
        StringEntity stringEntity = new StringEntity(body, ContentType.APPLICATION_JSON);
        stringEntity.setContentType(String.valueOf(ContentType.APPLICATION_JSON));
        stringEntity.setContentEncoding(ENCODING);
        return post(url, heads, stringEntity);
    }

    public static String post(String url, String body) {
        String result = "";
        try {
            result = post(url, null, body);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    public static String post(String url, Map<String, String> heads, HttpEntity httpEntity) {
        String resultString = "";
        HttpPost httpPost = new HttpPost(url);
        if (heads != null && !heads.isEmpty()) {
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        httpPost.setEntity(httpEntity);
        CloseableHttpClient httpClient = HttpConnectionManager.getHttpClientFactory().getHttpClient();
        try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
            return parseResult(httpResponse);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return resultString;
    }
    private static String parseResult(CloseableHttpResponse closeableHttpResponse) {
        String result = "";
        try {
            if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                Header[] headers = closeableHttpResponse.getAllHeaders();
                for (Header header : headers) {
                    System.out.println(header);
                }
                InputStream inputStream = closeableHttpResponse.getEntity().getContent();
                result = IOUtils.toString(inputStream, ENCODING);
                inputStream.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }
}

常见的工具类方法

https://blog.csdn.net/zhw864680355/article/details/100532964
提供以下常见的工具方法

  1. java正则表达式的匹配包括:邮箱,手机,姓名,昵称,身份证号,银行卡号等;
  2. 生成6位随机数;
  3. 对url中字符串进行编码和解码
  4. 获取客户端ip地址
  5. 获取系统当前时间
  6. 生成32位编码不含横线
  7. 生成MD5编码
  8. 通过身份证获取性别
  9. 通过身份证获取生日
  10. 通过身份证获取生日
  11. 手机号中间4位替换成星号
  12. 邮箱地址加星号
  13. 生成随机密码
package com.xiyuan.startingpoint.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.SecureRandom;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;




/**
* 通用工具类.
*/
public class CommonUtil {
    private static SecureRandom random = new SecureRandom();




    public static final Pattern MAIL_PATTERN = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");




    public static final Pattern MOBILE_PATTERN = Pattern.compile("^1[3|4|5|7|8][0-9]\\d{8}$");




    public static final Pattern NAME_PATTERN = Pattern.compile("^[\\u4E00-\\u9FBF][\\u4E00-\\u9FBF(.|·)]{0,13}[\\u4E00-\\u9FBF]$");




    public static final Pattern NICKNAME_PATTERN = Pattern.compile("^((?!\\d{5})[\\u4E00-\\u9FBF(.|·)|0-9A-Za-z_]){2,11}$");




    public static final Pattern PASSWORD_PATTERN = Pattern.compile("^[\\s\\S]{6,30}$");




    public static final Pattern CODE_PATTERN = Pattern.compile("^0\\d{2,4}$");




    public static final Pattern POSTCODE_PATTERN = Pattern.compile("^\\d{6}$");




    public static final Pattern ID_PATTERN = Pattern.compile("^\\d{6}(\\d{8}|\\d{11})[0-9a-zA-Z]$");




    public static final Pattern BANK_CARD_PATTERN = Pattern.compile("^\\d{16,30}$");




    /**
     * 生成6位随机数字, 用于手机短信验证码.
     *
     * @return 6位随机数字
     */
    public static int random() {
        int x = Math.abs(random.nextInt(899999));




        return x + 100000;
    }




    /**
     * 对url字符串进行编码.
     *
     * @param url 要编码的url字符串
     * @return 编码后的字符串
     */
    public static String urlEncoder(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        try {
            return java.net.URLEncoder.encode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }




    /**
     * 对url字符串进行解码.
     *
     * @param url 要解码的url字符串
     * @return 解码后的字符串
     */
    public static String urlDecoder(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        try {
            return URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }




    /**
     * 验证字符串是不是邮箱.
     *
     * @param email 要验证的邮箱
     * @return 是否正确邮箱
     */
    public static boolean validateEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        Matcher m = MAIL_PATTERN.matcher(email);
        return m.matches();
    }




    /**
     * 验证字符串是不是手机号.
     *
     * @param mobile 要验证的手机号
     * @return 是否正确手机号
     */
    public static boolean validateMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        Matcher m = MOBILE_PATTERN.matcher(mobile);
        return m.matches();
    }




    /**
     * 验证身份证是否有效.
     *
     * @param idCardNumber 要验证的身份证
     * @return 是否正确身份证
     */
    public static boolean validateId(String idCardNumber) {
        if (StringUtils.isEmpty(idCardNumber)) {
            return false;
        }
        Matcher m = ID_PATTERN.matcher(idCardNumber);
        return m.matches() && IdcardUtils.validateCard(idCardNumber);
    }




    /**
     * 验证姓名是否有效.
     *
     * @param name 要验证的姓名
     * @return 是否正确姓名
     */
    public static boolean validateName(String name) {
        if (StringUtils.isEmpty(name) || name.replaceAll("[^.·]", "").length() > 1) {
            return false;
        }
        Matcher m = NAME_PATTERN.matcher(name);
        return m.matches();
    }




    /**
     * 验证昵称是否有效.
     *
     * @param nickname 要验证的昵称
     * @return 是否正确昵称
     */
    public static boolean validateNickname(String nickname) {




        //规则 不能包含5个数字 允许中英文和数字 2-11位
        if (StringUtils.isEmpty(nickname) || nickname.replaceAll("[^0-9]", "").length() > 4) {
            return false;
        }
        Matcher m = NICKNAME_PATTERN.matcher(nickname);
        return m.matches();
    }




    /**
     * 验证密码格式是否有效.
     *
     * @param password 要验证的密码
     * @return 是否正确密码格式
     */
    public static boolean validatePassword(String password) {
        if (StringUtils.isEmpty(password)) {
            return false;
        }
        Matcher m = PASSWORD_PATTERN.matcher(password);
        return m.matches();
    }




    /**
     * 验证区号是否有效.
     *
     * @param code 要验证的区号
     * @return 是否正确身份证
     */
    
public static boolean validateCode(String code) {
        if (StringUtils.isEmpty(code)) {
            return false;
        }
        Matcher m = CODE_PATTERN.matcher(code);
        return m.matches();
    }


    /**
     * 验证邮政编码是否有效.
     *
     * @param postcode 要验证的邮政编码
     * @return 是否正确邮政编码
     */
    public static boolean validatePostcode(String postcode) {
        if (StringUtils.isEmpty(postcode)) {
            return false;
        }
        Matcher m = POSTCODE_PATTERN.matcher(postcode);
        return m.matches();
    }


    /**
     * 验证银行卡是否有效.
     *
     * @param bankCardNumber 要验证的银行卡号
     * @return 是否正确银行卡号
     */
    public static boolean validateBankCardNumber(String bankCardNumber) {
        if (StringUtils.isEmpty(bankCardNumber)) {
            return false;
        }
        Matcher m = BANK_CARD_PATTERN.matcher(bankCardNumber);
        return m.matches();
    }


    /**
     * 获取客户端IP地址.
     *
     * @param request request请求
     * @return ip地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("Cdn-Src-Ip");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (StringUtils.hasText(ip)) {
            return StringUtils.tokenizeToStringArray(ip, ",")[0];
        }
        return "";
    }


    /**
     * 获取当前系统时间,以java.sql.Timestamp类型返回.
     *
     * @return 当前时间
     */
    public static Timestamp getTimestamp() {
        Timestamp d = new Timestamp(System.currentTimeMillis());
        return d;
    }


    /**
     * 生成32位编码,不含横线
     *
     * @return uuid串
     */
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid.toUpperCase();
    }


    /**
     * 生成MD5编码
     *
     * @param data 要编码的字符串
     * @return 加密后的字符串
     */
    public static String md5(String data) throws IOException {
        return md5(data, 1);
    }




    /**
     * 生成MD5编码
     *
     * @param data 要编码的字符串
     * @param time 加密次数
     * @return 加密后的字符串
     */
    public static String md5(String data, int time) throws IOException{
        byte[] bytes = data == null ? new byte[0] : data.getBytes("UTF-8");


        while (time-- > 1) {
            bytes = DigestUtils.md5Digest(bytes);
        }


        return DigestUtils.md5DigestAsHex(bytes).toUpperCase();
    }


    /**
     * 空字符串转为null
     *
     * @param object 要规则化的对象
     * @param <T>    对象类型
     * @return 规则化后的对象
     */
    public static <T> T normalizeBlankStringFields(T object) {
        if (object == null) return null;


        PropertyUtilsBean utils = BeanUtilsBean.getInstance().getPropertyUtils();
        Stream.of(utils.getPropertyDescriptors(object)).forEach(pd -> {
            try {
                Object value = utils.getNestedProperty(object, pd.getName());
                if (value == null) return;


                if (!StringUtils.hasText(value.toString())) {
                    utils.setNestedProperty(object, pd.getName(), null);
                }
            } catch (Throwable e) {
            }
        });


        return object;
    }


    /**
     * 通过身份证获取性别
     *
     * @param idNumber 身份证号
     * @return 返回性别, 0 保密 , 1 男 2 女
     */
    public static Integer getGenderByIdNumber(String idNumber) {


        int gender = 0;


        if (idNumber.length() == 15) {
            gender = Integer.parseInt(String.valueOf(idNumber.charAt(14))) % 2 == 0 ? 2 : 1;
        } else if (idNumber.length() == 18) {
            gender = Integer.parseInt(String.valueOf(idNumber.charAt(16))) % 2 == 0 ? 2 : 1;
        }


        return gender;


    }


    /**
     * 通过身份证获取生日
     *
     * @param idNumber 身份证号
     * @return 返回生日, 格式为 yyyy-MM-dd 的字符串
     */
    public static String getBirthdayByIdNumber(String idNumber) {


        String birthday = "";


        if (idNumber.length() == 15) {
            birthday = "19" + idNumber.substring(6, 8) + "-" + idNumber.substring(8, 10) + "-" + idNumber.substring(10, 12);
        } else if (idNumber.length() == 18) {
            birthday = idNumber.substring(6, 10) + "-" + idNumber.substring(10, 12) + "-" + idNumber.substring(12, 14);
        }


        return birthday;


    }




    /**
     * 通过身份证获取年龄
     *
     * @param idNumber 身份证号
     * @return 返回年龄
     */
    public static Integer getAgeByIdNumber(String idNumber) {


        String birthString = getBirthdayByIdNumber(idNumber);
        if (StringUtils.isEmpty(birthString)) {
            return 0;
        }


        return getAgeByBirthString(birthString);


    }


    /**
     * 通过身份证获取年龄
     *
     * @param idNumber     身份证号
     * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
     * @return 返回年龄
     */
    public static Integer getAgeByIdNumber(String idNumber, boolean isNominalAge) {


        String birthString = getBirthdayByIdNumber(idNumber);
        if (StringUtils.isEmpty(birthString)) {
            return 0;
        }


        return getAgeByBirthString(birthString, isNominalAge);


    }


    /**
     * 通过生日日期获取年龄
     *
     * @param birthDate 生日日期
     * @return 返回年龄
     */
    public static Integer getAgeByBirthDate(Date birthDate) {


        return getAgeByBirthString(new SimpleDateFormat("yyyy-MM-dd").format(birthDate));


    }




    /**
     * 通过生日字符串获取年龄
     *
     * @param birthString 生日字符串
     * @return 返回年龄
     */
    public static Integer getAgeByBirthString(String birthString) {


        return getAgeByBirthString(birthString, "yyyy-MM-dd");


    }


    /**
     * 通过生日字符串获取年龄
     *
     * @param birthString  生日字符串
     * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
     * @return 返回年龄
     */
    public static Integer getAgeByBirthString(String birthString, boolean isNominalAge) {


        return getAgeByBirthString(birthString, "yyyy-MM-dd", isNominalAge);


    }


    /**
     * 通过生日字符串获取年龄
     *
     * @param birthString 生日字符串
     * @param format      日期字符串格式,为空则默认"yyyy-MM-dd"
     * @return 返回年龄
     */
    public static Integer getAgeByBirthString(String birthString, String format) {
        return getAgeByBirthString(birthString, "yyyy-MM-dd", false);
    }




    /**
     * 通过生日字符串获取年龄
     *
     * @param birthString  生日字符串
     * @param format       日期字符串格式,为空则默认"yyyy-MM-dd"
     * @param isNominalAge 是否按元旦算年龄,过了1月1日加一岁 true : 是 false : 否
     * @return 返回年龄
     */
    public static Integer getAgeByBirthString(String birthString, String format, boolean isNominalAge) {


        int age = 0;


        if (StringUtils.isEmpty(birthString)) {
            return age;
        }


        if (StringUtils.isEmpty(format)) {
            format = "yyyy-MM-dd";
        }


        try {


            Calendar birthday = Calendar.getInstance();
            Calendar today = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            birthday.setTime(sdf.parse(birthString));
            age = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
            if (!isNominalAge) {
                if (today.get(Calendar.MONTH) < birthday.get(Calendar.MONTH) ||
                        (today.get(Calendar.MONTH) == birthday.get(Calendar.MONTH) &&
                                today.get(Calendar.DAY_OF_MONTH) < birthday.get(Calendar.DAY_OF_MONTH))) {
                    age = age - 1;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }


        return age;


    }


    /**
     * 手机号中间四位替换成星号
     *
     * @param mobile
     * @return
     */
    public static String maskMobile(String mobile) {
        if (validateMobile(mobile)) {
            return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        }
        return mobile;
    }


    /**
     * 手机号中间四位自定义替换
     *
     * @param mobile
     * @param transCode 中间四位目标值 如GXJF 将136GXJF1111
     * @return
     */
    public static String maskMobile(String mobile, String transCode) {
        if (validateMobile(mobile)) {
            transCode = StringUtils.isEmpty(transCode) ? "****" : transCode;
            return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", String.format("$1%s$2", transCode));
        }
        return mobile;
    }


    /**
     * 邮箱地址加星号
     *
     * @param email
     * @return
     */
    public static String maskEmail(String email) {
        if (validateEmail(email)) {
            String userName = email.substring(0, email.indexOf("@"));
            int len = userName.length();
            if (len >= 5) {
                int total = len - 3;
                int half = total / 2;
                int start = half;
                int end = len - half;
                if (total % 2 != 0) {
                    end = end - 1;
                }
                StringBuilder sb = new StringBuilder(email);
                for (int i = start; i < end; i++) {
                    sb.setCharAt(i, '*');
                }
                return sb.toString();
            }
        }
        return email;
    }


    /**
     * 账号中间四位自定义替换
     *
     * @param account
     * @return
     */
    public static String maskTradeAccount(String account) {
        return account.replaceAll("(\\d{7})\\d*(\\d{4})", "$1****$2");
    }




    /**
     * 验证是否为日期
     *
     * @param date
     * @return
     */
    public static boolean validateDate(String date) {
        boolean convertSuccess = true;
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        try {
            format.setLenient(false);
            format.parse(date);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }


    /**
     * 获取时间戳,作为递增的ID
     */
    private static final Lock lock = new ReentrantLock();   //锁对象


    public static long getUniqueLong() {
        long l;
        lock.lock();
        try {
            l = System.currentTimeMillis();
        } finally {
            lock.unlock();
        }
        return l;
    }


    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123",解析出Action:del,id:123存入map中
     *
     * @param URL url地址
     * @return url请求参数部分
     */
    public static String getUrlParams(String URL, String key) {
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit = null;
        String strUrlParam = null;
        java.net.URL aURL = null;
        try {
            aURL = new URL(URL);
            strUrlParam = aURL.getQuery();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        if (strUrlParam == null) {
            return "";
        }
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");
            if (arrSplitEqual.length > 1) {
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (!StringUtils.isEmpty(arrSplitEqual[0])) {
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        if (mapRequest.containsKey(key)) {
            try {
                return URLDecoder.decode(mapRequest.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {


            }
        }
        return "";
    }

    /**
     * 生成随机密码
     *
     * @param pwd_len 生成的密码的总长度
     * @return 密码的字符串
     */
    public static String genRandomNum(int pwd_len) {
        // 35是因为数组是从0开始的,26个字母+10个数字
        final int maxNum = 36;
        int i; // 生成的随机数
        int count = 0; // 生成的密码的长度
        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < pwd_len) {
            // 生成随机数,取绝对值,防止生成负数,
            i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }
}

邮件发送工具类

邮件工具类是通过JavaEmail实现,企业级项目一般都会专门的服务去发送邮件,但如果自己的小Demo,用工具类发送Email也未尝不可。示例Demo如下,有兴趣的可以fork代码自己研究一下,代码有详情的注释。

public class EmailUtilTest {
    @Before
    public void before() throws GeneralSecurityException {
        // 发送邮箱配置,授权密码可以去邮件运营商获取
        EmailUtil.config(EmailUtil.SMTP_QQ(false), "xxx@qq.com", "xxxxxx");
    }
 
    @Test
    public void testSendText() throws MessagingException {
        System.out.println("test");
    }
 
}
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-08-22 13:25:07  更:2021-08-22 13:25:11 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 9:09:57-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码