常用工具类-commons-lang3

常用工具类-commons-lang3

1.依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

2.字符串-StringUtils

public static void stringUtils() {
    String s1 = "hello world";
    // 缩写,将多余的部分替换为 ...
    String abbreviate = StringUtils.abbreviate(s1, 6);
    System.out.println(abbreviate); // hel...

    // 第一个字母大写
    String capitalize = StringUtils.capitalize(s1);
    System.out.println(capitalize);

    // 追加,以2结尾返回,原字符串;不以2结尾,在h1后面追加2
    String appendIfMissing1 = StringUtils.appendIfMissing("h1", "2");
    System.out.println(appendIfMissing1); //h12

    // 替换字符串的中间部分
    String abbreviateMiddle = StringUtils.abbreviateMiddle("15829551111", "****", 10);
    System.out.println(abbreviateMiddle); // 158****111

    // 扩展字符串
    String center = StringUtils.center("12", 6, "k");
    System.out.println(center); // kk12kk

    // 去掉 \r 转义字符
    String chomp = StringUtils.chomp("123\r");
    System.out.println(chomp); // 123

    // null -> ""
    String defaultString = StringUtils.defaultString(null);
    System.out.println(defaultString); // ""

    String chop = StringUtils.chop("123");
    System.out.println(chop); // 12

    System.out.println("=============");
    // 第二个字符串和第一的不同,从第一字符串索引为1开始比较
    String difference = StringUtils.difference("12345", "15678");
    System.out.println(difference); // 5678

    // 获取数字
    String digits = StringUtils.getDigits("a1d23");
    System.out.println(digits); // 123

    boolean blank = StringUtils.isBlank(" ");
    System.out.println(blank); // true
    boolean empty = StringUtils.isEmpty(" ");
    System.out.println(empty); // false

    // 是字符
    boolean alpha = StringUtils.isAlpha("adf)");
    System.out.println(alpha); // false

    // 只有字母和数字
    boolean alphanumeric = StringUtils.isAlphanumeric("abc");
    System.out.println(alphanumeric); // true

    // 是否是大小写混合的
    boolean mixedCase = StringUtils.isMixedCase("aBc");
    System.out.println(mixedCase); // true

    String format = String.format("12 %s 13 %s 14 %d", "a", "b", 1);
    System.out.println(format);
}

3.日期-DateUtils

public class DateDemo {

    public static void main(String[] args) {
        //stringToDate();
        //dateAdd();
        //instantAndDateConvert();
        //instantAdd();
        //localDate();
        //localTime();
        localDateTime();
    }

    public static void localDateTime() {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now); // 2021-12-07T16:20:59.301

        // 加10天
        LocalDateTime _10 = now.plusDays(10);
        System.out.println(_10); // 2021-12-17T16:20:59.301

        // 时间比较
        if (now.isBefore(_10)) { // true
            System.out.println("now 在 _10 之前");
        }

        // 格式转换
        String s1 = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(s1); // 2021-12-07 16:20:59

        String s2 = now.format(DateTimeFormatter.ISO_DATE_TIME);
        System.out.println(s2); // 2021-12-07T16:20:59.301

        // 转换
        // LocalDateTime to Date
        Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
        Date date = Date.from(instant);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        System.out.println(format); // 2021-12-07 16:20:59

        // Date To LocalDateTime
        Date nowDate = new Date();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(nowDate.toInstant(), ZoneId.systemDefault());
        System.out.println(localDateTime); // 2021-12-07T16:20:59.329
    }

    public static void localTime() {
        LocalTime now = LocalTime.now();
        System.out.println(now); // 16:03:59.251

        // 加10小时
        LocalTime _10 = now.plusHours(10); // 02:03:59.251
        System.out.println(_10);
    }

    public static void localDate() {
        LocalDate now = LocalDate.now();
        System.out.println(now); // 2021-12-07

        System.out.println(now.lengthOfYear()); // 365

        // 加10天
        LocalDate _10 = now.plusDays(10);
        // LocalData使用final修改,不可变,操作之后会生成一个新对象
        System.out.println(now); // 2021-12-07
        System.out.println(_10); // 2021-12-17

        // 格式化
        String s1 = now.format(DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(s1); // 20211207

        String s2 = now.format(DateTimeFormatter.ofPattern("yyyy--MM--dd"));
        System.out.println(s2); // 2021--12--07
    }

    public static void instantAdd() {
        long second = 1000;
        long minute = second * 60;
        long hour = minute * 60;
        long day = hour * 24;

        System.out.println(new Date().getTime()); // 1638862868672 2021-12-07 15:41
        Instant instant = Instant.ofEpochMilli(1638862868672L);
        System.out.println(instant); // 2021-12-07T07:41:08.672Z

        // 加一天
        Instant millis = instant.plusMillis(day);
        // Instant使用final修改,不可变,操作后会生成一个新对象
        System.out.println(instant); // 2021-12-07T07:41:08.672Z
        System.out.println(millis); // 2021-12-08T07:41:08.672Z
    }

    public static void instantAndDateConvert() {
        // Instant to Date
        Instant instant = Instant.now();
        System.out.println(instant); // 2021-12-07T07:38:35.189Z

        Date now = Date.from(instant); // 对时区进行自动转 +8小时
        System.out.println(now); // Tue Dec 07 15:37:35 CST 2021

        // Date to Instant
        Instant toInstant = now.toInstant();
        System.out.println(toInstant); // 2021-12-07T07:39:29.644Z
    }

    public static void dateAdd() {
        long second = 1000;
        long minute = second * 60;
        long hour = minute * 60;
        long day = hour * 24;

        // 当前时间
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(now);
        System.out.println(format); // 2021-12-07 15:24:37

        // 通过加减毫秒数进行时间的加减
        long nextDay = now.getTime() + day;
        Date nextDate = new Date(nextDay);
        System.out.println(sdf.format(nextDate)); // 2021-12-08 15:25:53
    }

    public static void stringToDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = "2021-12-07 15:10:55";
        Date date = null;
        try {
            date = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public static void dateToString() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        System.out.println(format);
    }
}

4.反射

  1. 获取注解中的值。
public static void getAnnotation() throws Exception {
        Field[] declaredFields = User.class.getDeclaredFields();
        for (Field field : declaredFields) {
            String name = field.getName();

            Value annotation = field.getAnnotation(Value.class);
            String value = annotation.value();

            System.out.println("name" + name + " - " + value);
        }
    }
  1. 反射-缺省
public static void introspector(Apple apple) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(apple.getClass());

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            // 属性名
            String fieldName = propertyDescriptor.getName();
            if (fieldName.endsWith("Name")) {
                Method readMethod = propertyDescriptor.getReadMethod();

                Object invoke = readMethod.invoke(apple);
                if (invoke instanceof Integer) {
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(apple, 10);
                }
            }
        }
    } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
        e.printStackTrace();
    }
}

5.Get和Post请求

/*
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.3</version>
</dependency>
*/
public static String get() throws IOException, URISyntaxException {
    String idCard = "123456xxx";
    String beginTime = "2000-01-02 14:30:00";
    String endTime = "2022-01-04 12:33:00";
    String cookie = "JSESSIONID=123456xxx";
    String urlPath = "https://localhost:8080/get/id/card/";

    CloseableHttpClient client = HttpClients.createDefault();
    String realUrl = urlPath + idCard + "?beginTime=" + beginTime + "&endTime=" + endTime;
    // 使用URL对拼接的请求进行包装,否则由于Get请求时请求地址中有空格会出现异常。
    // Caused by: java.net.URISyntaxException:
    // Illegal character in query at index 65:
    // https://localhost:8080/get/id/card/123456xxx?beginTime=2000-01-02 14:30:00&endTime=2022-01-04 12:33:00
    URL url = new URL(realUrl);
    URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
    HttpGet httpGet = new HttpGet(uri);
    httpGet.setHeader("Cookie", cookie);

    try (CloseableHttpResponse response = client.execute(httpGet)) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity resEntity = response.getEntity();
            return EntityUtils.toString(resEntity);
        }
    } catch (Exception e) {
        log.info("e ", e);
    }
    return null;
}

7.发送请求-携带请求body

/*
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>fluent-hc</artifactId>
	<version>4.5.13</version>
</dependency>
*/
public static void post() {
    // 请求URL
    String url = "http://127.0.0.1:8080/user";
    // 请求body
    String body = "body";
    try {
        Content response = Request.Post(url).bodyByteArray(body.getBytes())
            .execute().returnContent();

        // 输出响应
        System.out.println(response.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
posted @ 2022-01-07 14:48  行稳致远方  阅读(116)  评论(0)    收藏  举报