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之后,将日期和时间分为​ ​LocateDate​​、​ ​LocalTime​​和​ ​LocalDateTime​​,相比​ ​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<String> 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<String> list1 = Arrays.asList(array1);
        List<String> 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 所依赖的 jar 包较少 ,简单易用;
  • 与其他 json 的框架如 Gson 相比, Jackson 解析大的 json 文件速度比较快;
  • Jackson 运行时占用内存比较低,性能比较好;
  • Jackson 比较灵活,容易进行扩展和定制。

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

  • jackson-core,核心包,提供基于流模式解析的相关 API;
  • jackson-annotations,注解包,提供标准注解功能;
  • jackson-databind ,数据绑定包, 提供基于对象绑定( ObjectMapper ) 解析的相关 API 和树模型(JsonNode)解析的相关 API ,这两个解析方式都依赖基于流模式解析的 API。

下面看看​ ​Jackson​​常用的注解。

  • ​ ​@JsonProperties​​。此注解指定一个属性用于json映射,默认情况下映射的JSON属性与注解的属性名称相同,可以使用此注解的​ ​value​​值修改json属性名。此外,该注解还有一个​ ​index​​属性,用于指定生成json属性的顺序。
  • ​ ​@JsonIgnore​​。用于排除某个属性,使得该属性不会被Jackson序列化和反序列化。
  • ​ ​JsonFormat​​。指定属性在序列化时转换成指定的格式。例如:​ ​@JsonFormat(pattern = "yyyy-MM-dd") ​​,表明属性在序列化时,会转换成​ ​yyyy-MM-dd​​这样的格式。
  • ​ ​@JsonPropertyOrder​​。作用与​ ​@JsonProperty​​的​ ​index​​属性类似,用于指定属性序列化时的顺序。

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

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

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

当添加 ​ ​jackson-databind​​ 之后, ​ ​jackson-core​​ 和 ​ ​jackson-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-io​​的​ ​FileUtils​​可以大大简化文件操作的开发工作量。

首先引入​ ​commons-io​​依赖:

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

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

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<String>
        // 输出[大彬, 最强]
        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")); //永远不会抛出异常,传入的路径是文件夹,则会删除文件夹下所有文件
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值