超级实用的Java工具类

大家好,我是大彬~

在平时开发过程中,经常会重复“造轮子”,在同一个项目里面,可能会出现各种各样每个人自己实现的工具类,这样不仅降低了开发效率,而且代码也不好维护。

今天趁着国庆假期,整理了一些常用的工具类,在这里给大家分享一下,希望对大家有所帮助~

字符串工具类

首先介绍一下commons-lang3的一个字符串工具类StringUtils,常用方法如下:

1、isEmpty() 判断字符串是否为空。

public class StringUtilsTest {
    public static void main(String[] args) {
        String name = "大彬";
        System.out.println(StringUtils.isEmpty(name));
    }
}

2、isBlank() 判断字符串是否为空,如果字符串都是空格,也认为是空。

public class StringUtilsTest {
    public static void main(String[] args) {
        System.out.println(StringUtils.isBlank("  "));
    }
    /**
     * true
     */
}

3、strip() 将字符串左右两边的空格删除。

public class StringUtilsTest {
    public static void main(String[] args) {
        String name = " 大彬 ";
        System.out.println(StringUtils.strip(name));
    }
}

4、join(Object[] array, String separator) 将数组拼接成字符串,可以设置分隔符。

public class StringUtilsTest {
    public static void main(String[] args) {
        String[] nameArr = {"大彬1", "大彬2", "大彬3"};
        System.out.println(StringUtils.join(nameArr, ","));
    }
    /**
     * output
     * 大彬1,大彬2,大彬3
     */
}

5、replace(String text, String searchString, String replacement)替换字符串关键字。

public class StringUtilsTest {
    public static void main(String[] args) {
        System.out.println(StringUtils.replace("hello, 大彬", "hello", "hi"));
    }
    /**
     * output
     * hi, 大彬
     */
}

日期工具类

SimpleDateFormat 不是线程安全的,在多线程环境会有并发安全问题,不推荐使用。这里大彬推荐另一个时间工具类DateFormatUtils,用于解决日期类型和字符串的转化问题,DateFormatUtils不会有线程安全问题。

Date 转化为字符串:

public class DateFormatUtilsTest {
    public static void main(String[] args) throws ParseException {
        String dateStr = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        System.out.println(dateStr);
    }
    /**
     * output
     * 2021-10-01
     */
}

字符串转 Date,可以使用commons-lang3 下时间工具类DateUtils。

public class DateUtilsTest {
    public static void main(String[] args) throws ParseException {
        String dateStr = "2021-10-01 15:00:00";
        Date date = DateUtils.parseDate(dateStr, "yyyy-MM-dd HH:mm:ss");
        System.out.println(date);
    }
    /**
     * output
     * Fri Oct 01 15:00:00 CST 2021
     */
}

Java8之后,将日期和时间分为LocateDateLocalTimeLocalDateTime,相比Date类,这些类都是final类型的,不能修改,也是线程安全的。

使用LocateDateTime获取年月日:

public class LocalDateTimeTest {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now.getYear());
        System.out.println(now.getMonthValue());
        System.out.println(now.getDayOfMonth());
    }
    /**
     * output
     * 2021
     * 10
     * 1
     */
}

使用LocalDateTime进行字符串和日期的转化:

public class LocalDateTimeTest1 {
    public static void main(String[] args) {
        String datePattern = "yyyy-MM-dd HH:mm:ss";
        //将字符串转化为日期
        LocalDateTime dateTime = LocalDateTime.parse("2021-10-01 16:00:00", DateTimeFormatter.ofPattern(datePattern));
        System.out.println(dateTime);
        //将LocalDateTime格式化为字符串
        String dateStr = DateTimeFormatter.ofPattern(datePattern).format(dateTime);
        System.out.println(dateStr);
    }
    /**
     * output
     * 2021-10-01T16:00
     * 2021-10-01 16:00:00
     */
}

集合工具类

在开发接口功能的时候,经常需要对入参做判空处理:

if (null == list || list.isEmpty()) {
}

虽然代码很简单,但是也比较容易写出抛空指针异常的代码。推荐使用commons-collections提供的工具类,使用简单,并且不会出错。

public class CollectionUtilsTest {
    public static void main(String[] args) {
        List nameList = new ArrayList<>();

        if (CollectionUtils.isEmpty(nameList)) {
            System.out.println("name list is empty");
        }
    }
}

Map集合判空使用commons-collections下的MapUtils工具类。数组判空需要使用commons-lang下的ArrayUtils

//map判空
if (MapUtils.isEmpty(map)) { 
}
//数组判空
if (ArrayUtils.isEmpty(array)) {  
}

此外,还可以使用CollectionUtils对基础数据类型和String类型的集合进行取交集、并集和差集的处理。

public class CollectionUtilsTest1 {
    public static void main(String[] args) {
        String[] array1 = new String[] { "1", "2", "3", "4"};
        String[] array2 = new String[] { "4", "5", "6", "7" };
        List list1 = Arrays.asList(array1);
        List list2 = Arrays.asList(array2);

        //并集 union
        System.out.println(CollectionUtils.union(list1, list2));
        //output: [1, 2, 3, 4, 5, 6, 7]

        //交集 intersection
        System.out.println(CollectionUtils.intersection(list1, list2));
        //output:[4]
    }
}

数组工具类

ArrayUtils 是专门处理数组的类,方便进行数组操作,不再需要各种循环操作。

数组合并操作:

public class ArrayUtilsTest {
    public static void main(String[] args) {
        //合并数组
        String[] arr1 = new String[]{"大彬1", "大彬2"};
        String[] arr2 = new String[]{"大彬3", "大彬4"};
        String[] arr3 = ArrayUtils.addAll(arr1, arr2);
        System.out.println(ArrayUtils.toString(arr3));
    }
    /**
     * output
     * {大彬1,大彬2,大彬3,大彬4}
     */
}

数组clone操作:

public class ArrayUtilsTest1 {
    public static void main(String[] args) {
        //合并数组
        String[] arr1 = new String[]{"大彬1", "大彬2"};
        String[] arr2 = ArrayUtils.clone(arr1);
        arr1[1] = "大彬";
        System.out.println("arr1:" + ArrayUtils.toString(arr1));
        System.out.println("arr2:" + ArrayUtils.toString(arr2));
    }
    /**
     * output
     * arr1:{大彬1,大彬}
     * arr2:{大彬1,大彬2}
     */
}

将数组原地翻转:

/**
 * @author: 程序员大彬
 * @time: 2021-10-01 19:29
 */
public class ArrayUtilsTest2 {
    public static void main(String[] args) {
        //将arr1翻转
        String[] arr1 = new String[]{"大彬1", "大彬2"};
        ArrayUtils.reverse(arr1);
        System.out.println(ArrayUtils.toString(arr1));
    }
    /**
     * output
     * {大彬2,大彬1}
     */
}

Json工具类

Jackson 是当前用的比较广泛的,用来序列化和反序列化 json 的开源框架。Jackson 优点如下:

Jackson 的核心模块由三部分组成。

下面看看Jackson常用的注解。

接下来看一下 Jackson 怎么使用。

首先要使用 Jackson 提供的功能,需要先添加依赖:


    com.fasterxml.jackson.core
    jackson-databind
    2.9.1

当添加 jackson-databind 之后, jackson-corejackson-annotations 也会被添加到 Java 项目工程中。

先介绍下对象绑定ObjectMapper的使用。如下代码,ObjectMapper 通过writeValue 方法 将对象序列化为 json,并将 json 存储成 String 格式。通过 readValue 方法将 json 反序列化为对象。

public class JsonUtilsTest {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Person person = new Person();
        person.setName("大彬");
        person.setAge(18);
        //对象序列化为json
        String jsonStr = mapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(person);
        System.out.println(jsonStr);
        //json反序列化为对象
        Person deserializedPerson = mapper.readValue(jsonStr, Person.class);
        System.out.println(deserializedPerson);
    }
    /**
     * output
     * {
     *   "name" : "大彬",
     *   "age" : 18
     * }
     * Person(name=大彬, age=18)
     */
}

ObjectMapper既可以处理简单数据类型,也能处理对象类型,但是有些情况下,比如我只想要 json 里面某一个属性的值,或者我不想创建一个POJO与之对应,只是临时使用,这时使用树模型JsonNode可以解决这些问题。

Object转换为JsonNode

public class JsonNodeTest {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();

        Person person = new Person();
        person.setName("大彬");
        person.setAge(18);

        JsonNode personJsonNode = objectMapper.valueToTree(person);
        //取出name属性的值
        System.out.println(personJsonNode.get("name"));
    }
    /**
     * output
     * "大彬"
     */
}

JsonNode转换为Object

public class JsonNodeTest1 {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String personJson = "{ "name" : "大彬", "age" : 18 }";
        JsonNode personJsonNode = objectMapper.readTree(personJson);

        Person p = objectMapper.treeToValue(personJsonNode, Person.class);
        System.out.println(p);
    }
    /**
     * output
     * Person(name=大彬, age=18)
     */
}

文件工具类

在平时工作当中,经常会遇到很多文件的操作,借助commons-ioFileUtils可以大大简化文件操作的开发工作量。

首先引入commons-io依赖:


    commons-io
    commons-io
    2.5

读文件操作代码如下,其中,:

public class FileUtilsTest {
    public static void main(String[] args) throws IOException {
        //输出:
        //大彬
        //最强
        System.out.println(FileUtils.readFileToString(new File("E:/demo.txt"), "UTF-8"));
        //readLines返回List
        // 输出[大彬, 最强]
        System.out.println(FileUtils.readLines(new File("E:/demo.txt"), "UTF-8"));
    }
}

写文件操作:

public class FileUtilsTest1 {
    public static void main(String[] args) throws IOException {
        //第一个参数File对象
        //第二个参数是写入的字符串
        //第三个参数是编码方式
        //第四个参数是是否追加模式
        FileUtils.writeStringToFile(new File("E://Demo.txt"), "大彬", "UTF-8",true);
    }
}

删除文件/文件夹操作:

FileUtils.deleteDirectory(new File("E://test"));
FileUtils.deleteQuietly(new File("E://test")); //永远不会抛出异常,传入的路径是文件夹,则会删除文件夹下所有文件

参考链接

https://juejin.cn/post/6844904154113146894

https://www.cnblogs.com/guanbin-529/p/11488869.html

展开阅读全文

页面更新:2024-03-16

标签:工具   注解   数组   字符串   绑定   序列   属性   对象   参数   日期   类型   操作   代码   格式   文件   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top