Java常用第三方工具类

本文章已经生成可运行项目,

一、Apache StringUtils:专为Java字符串而生的工具类

首先引入依赖:

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

1.字符串判空

isEmpty: 判断null和""

isNotEmpty:判断null和""

isBlank:判断null和""和" "

isNotBlank:判断null和""和" "

示例代码如下:

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: StringUtils测试
 */
@SpringBootTest
public class StringTest {

    @Test
    void test1() {
        String str1 = null;
        String str2 = "";
        String str3 = " ";
        String str4 = "abc";
        String str5 = "null";

        System.out.println(StringUtils.isEmpty(str1));
        System.out.println(StringUtils.isEmpty(str2));
        System.out.println(StringUtils.isEmpty(str3));
        System.out.println(StringUtils.isEmpty(str4));
        System.out.println(StringUtils.isEmpty(str5));

        System.out.println("=====");
        System.out.println(StringUtils.isNotEmpty(str1));
        System.out.println(StringUtils.isNotEmpty(str2));
        System.out.println(StringUtils.isNotEmpty(str3));
        System.out.println(StringUtils.isNotEmpty(str4));
        System.out.println(StringUtils.isNotEmpty(str5));

        System.out.println("=====");
        System.out.println(StringUtils.isBlank(str1));
        System.out.println(StringUtils.isBlank(str2));
        System.out.println(StringUtils.isBlank(str3));
        System.out.println(StringUtils.isBlank(str4));
        System.out.println(StringUtils.isBlank(str5));

        System.out.println("=====");
        System.out.println(StringUtils.isNotBlank(str1));
        System.out.println(StringUtils.isNotBlank(str2));
        System.out.println(StringUtils.isNotBlank(str3));
        System.out.println(StringUtils.isNotBlank(str4));
        System.out.println(StringUtils.isNotBlank(str5));
    }
}

执行结果:

true
true
false
false
false
=====
false
false
true
true
true
=====
true
true
true
false
false
=====
false
false
false
true
true

2.分割字符串

使用StringUtils的split()方法分割字符串成数组。

示例代码如下:

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: StringUtils测试
 */
@SpringBootTest
public class StringTest {

    @Test
    void test1() {
        String result = "a,b,c";
        String[] arr = StringUtils.split(result, ",");
        // 输出[a, b, c]
        System.out.println(Arrays.toString(arr));
    }
}

3.判断是否纯数字

使用StringUtils的isNumeric()方法判断字符串是否是纯数字形式。

示例代码如下:

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;


/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: StringUtils测试
 */
@SpringBootTest
public class StringTest {

    @Test
    void test1() {
        String data1 = "2";
        // 输出true
        System.out.println(StringUtils.isNumeric(data1));
        String data2 = "hello";
        // 输出false
        System.out.println(StringUtils.isNumeric(data2));
    }
}

4.将集合拼接成字符串

使用StringUtils的join(list,"拼接的字符")方法将集合的数据拼接成字符串。

示例代码如下:

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;


/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: StringUtils测试
 */
@SpringBootTest
public class StringTest {

    @Test
    void test1() {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        // 输出a,b,c
        System.out.println(StringUtils.join(list, ","));
    }
}

5.其他方法

  • trim(String str):去除字符串首尾的空白字符。
  • trimToEmpty(String str):去除字符串首尾的空白字符,如果字符串为 null,则返回空字符串。
  • trimToNull(String str):去除字符串首尾的空白字符,如果结果为空字符串,则返回 null。
  • equals(String str1, String str2):比较两个字符串是否相等。
  • equalsIgnoreCase(String str1, String str2):比较两个字符串是否相等,忽略大小写。
  • startsWith(String str, String prefix):检查字符串是否以指定的前缀开头。
  • endsWith(String str, String suffix):检查字符串是否以指定的后缀结尾。
  • contains(String str, CharSequence seq):检查字符串是否包含指定的字符序列。
  • indexOf(String str, CharSequence seq):返回指定字符序列在字符串中首次出现的索引,如果没有找到,则返回 -1。
  • lastIndexOf(String str, CharSequence seq):返回指定字符序列在字符串中最后一次出现的索引,如果没有找到,则返回 -1。
  • substring(String str, int start, int end):截取字符串中指定范围的子串。
  • replace(String str, String searchString, String replacement):替换字符串中所有出现的搜索字符串为指定的替换字符串。
  • replaceAll(String str, String regex, String replacement):使用正则表达式替换字符串中所有匹配的部分。
  • join(Iterable<?> iterable, String separator):使用指定的分隔符将可迭代对象中的元素连接为一个字符串。
  • split(String str, String separator):使用指定的分隔符将字符串分割为一个字符串数组。
  • capitalize(String str):将字符串的第一个字符转换为大写。
  • uncapitalize(String str):将字符串的第一个字符转换为小写。

二、Hutool工具包

引入依赖:

<!--hutool-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.12</version>
</dependency>

1.类型转换

我们接收客户端传过来的数据的时候,通常我们需要把这些数据转换成我们需要的数据类型。

示例代码如下:

import cn.hutool.core.convert.Convert;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {

    @Test
    void test1() {
        String param = null;
        // 输出null
        System.out.println(Convert.toInt(param));
        // 设置了默认值 输出0
        System.out.println(Convert.toInt(param, 0));
        
        // 输出Fri Jun 09 00:00:00 CST 2023
        System.out.println(Convert.toDate("2023年06月09日"));
    }
}

2.日期时间转换

示例代码如下:

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {

    @Test
    void test1() {
        // 输出2023-06-09 09:55:24
        System.out.println(DateUtil.date());
        // 输出2023-06-09 00:00:00
        DateTime dateTime = DateUtil.parse("2023-06-09");
        System.out.println(dateTime);

        // 输出2023-06-09
        Date date = new Date();
        System.out.println(DateUtil.formatDate(date));
    }
}

3.反射工具

Hutool 封装的反射工具 ReflectUtil 包括:

  • 获取构造方法
  • 获取字段
  • 获取字段值
  • 获取方法
  • 执行方法(对象方法和静态方法)

示例代码如下:

import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: ReflectUtil测试
 */
public class ReflectTest {
    private int id;

    public ReflectTest() {
        System.out.println("构造方法");
    }

    public void show() {
        System.out.println("普通方法");
    }


    public static void main(String[] args) throws IllegalAccessException {
        // 获取对象
        ReflectTest reflectTest = ReflectUtil.newInstance(ReflectTest.class);
        reflectTest.show();

        // 构造方法
        Constructor[] constructors = ReflectUtil.getConstructors(ReflectTest.class);
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName());
        }

        // 获取字段
        Field field = ReflectUtil.getField(ReflectTest.class, "id");
        field.setInt(reflectTest, 20);
        // 输出20
        System.out.println(ReflectUtil.getFieldValue(reflectTest, field));

        Method[] methods = ReflectUtil.getMethods(ReflectTest.class);
        for (Method method : methods) {
            System.out.println(method.getName());
        }
        // 获取指定方法
        Method method = ReflectUtil.getMethod(ReflectTest.class, "show");
        System.out.println(method.getName());

        // 执行方法 输出普通方法
        ReflectUtil.invoke(reflectTest, "show");

    }
}

4.身份证工具

使用IdcardUtil的isValidCard验证身份证是否合法。

示例代码如下:

import cn.hutool.core.util.IdcardUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;


/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {

    @Test
    void test1() {
        // 输出false
        System.out.println(IdcardUtil.isValidCard("43243"));
    }
}

5.字段验证器

验证客户端传过来的数据,比如手机号码、邮箱、IP地址等是否合法。

示例代码如下:

import cn.hutool.core.lang.Validator;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;


/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {

    @Test
    void test1() {
        String email = "hello@qq.com";
        // 输出true
        System.out.println(Validator.isEmail(email));

        String mobile = "1887888";
        // 输出false
        System.out.println(Validator.isMobile(mobile));

        String ip = "192.168";
        // 输出false
        System.out.println(Validator.isIpv4(ip));
    }
}

6.缓存工具

CacheUtil 是 Hutool 封装的创建缓存的快捷工具类,可以创建不同的缓存对象:

  • FIFOCache:先入先出,元素不停的加入缓存直到缓存满为止,当缓存满时,清理过期缓存对象,清理后依旧满则删除先入的缓存。
  • LFUCache,最少使用,根据使用次数来判定对象是否被持续缓存,当缓存满时清理过期对象,清理后依旧满的情况下清除最少访问的对象并将其他对象的访问数减去这个最少访问数,以便新对象进入后可以公平计数。
  • LRUCache,最近最久未使用,根据使用时间来判定对象是否被持续缓存,当对象被访问时放入缓存,当缓存满了,最久未被使用的对象将被移除。

示例代码如下:

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;


/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {

    @Test
    void test1() {
        Cache<String, String> fifoCache = CacheUtil.newFIFOCache(3);
        fifoCache.put("key1", "a");
        fifoCache.put("key2", "b");
        fifoCache.put("key3", "c");
        fifoCache.put("key4", "d");

        // 缓存大小为 3,所以 key4 放入后 key1 被清除 输出null
        System.out.println(fifoCache.get("key1"));
        // 输出b
        System.out.println(fifoCache.get("key2"));


        Cache<String, String> lfuCache = CacheUtil.newLFUCache(3);
        lfuCache.put("key1", "a");
        // 使用次数+1
        lfuCache.get("key1");
        lfuCache.put("key2", "b");
        lfuCache.put("key3", "c");
        lfuCache.put("key4", "d");
        // 由于缓存容量只有 3,当加入第 4 个元素的时候,最少使用的将被移除(2,3被移除)
        // 都是输出null
        System.out.println(lfuCache.get("key2"));
        System.out.println(lfuCache.get("key3"));


        Cache<String, String> lruCache = CacheUtil.newLRUCache(3);
        lruCache.put("key1", "a");
        lruCache.put("key2", "b");
        lruCache.put("key3", "c");
        // 使用时间近了
        lruCache.get("key1");
        lruCache.put("key4", "d");

        // 由于缓存容量只有 3,当加入第 4 个元素的时候,最久使用的将被移除(2)
        String value2 = lruCache.get("key2");
        // 输出null
        System.out.println(value2);
    }
}

三、Guava:Google开源的Java工具库 

引入依赖

<!--guava-->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

1.字符串处理

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Optional;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: Guava测试
 */
@SpringBootTest
public class GuavaTest {

    @Test
    void test() {
        // 1.字符串拼接
        Joiner joiner = Joiner.on(",");
        // 输出hello,world,qq
        System.out.println(joiner.join("hello", "world", "qq"));

        // 2.字符串拆分
        String data = "hello,world,qq";
        // 输出[hello, world, qq]
        System.out.println(Splitter.on(",").splitToList(data));
    }
}

2.集合工具

示例代码如下:

import com.google.common.collect.Lists;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: Guava测试
 */
@SpringBootTest
public class GuavaTest {

    @Test
    void test() {
        // 创建空集合
        List<Integer> emptyList = Lists.newArrayList();
        // 初始化集合
        List<Integer> initList = Lists.newArrayList(1, 2, 3);

        // 输出[]
        System.out.println(emptyList);
        // 输出[1, 2, 3]
        System.out.println(initList);
    }
}

本文已生成可运行项目
原文:https://github.com/yangchenjava/com.yangc.utils cache EhCacheUtils - 基于ehcache的工具类 LruCacheUtils - 基于LinkedHashMap实现LRU缓存的工具类 MemcachedUtils - 基于memcached的工具类 RedisUtils - 基于redis的工具类,与redis的集群配置无缝结合 db JdbcUtils - 操作jdbc的工具类 MongodbUtils - 操作mongodb的工具类 email EmailUtils - 邮件工具类,支持发送带附件的邮件 encryption AesUtils - 实现AES加密解密 Base64Utils - 实现Base64加密解密 Md5Utils - 获取字符串或文件的md5 excel ReadExcel2003 - 以model方式读2003版Excel(大数据) ReadExcel2007 - 以sax方式读2007版Excel(大数据) WriteExcel - 写Excel image CaptchaUtils - 生成验证码 ImageUtils - 图片压缩、截图 QRCodeUtils - 生成二维码、解析二维码 io SerializeUtils - 序列化、反序列化对象 ZipUtils - 压缩、解压文件 json JsonUtils - json格式转换 lang CharsetDetectorUtils - 获取文本文件编码格式 ChineseCalendar - 农历日历 ConvertUtils - 高低字节转换 DateUtils - 日期工具类 HtmlFilterUtils - 过滤html标签 JsoupUtils - 基于jsoup过滤html标签 MoneyUtils - 获取大写金额 NumberUtils - 数字工具类 PinyinUtils - 汉字转拼音 media MediaUtils - 基于ffmpeg,qtfaststart,yamdi的多媒体工具类 net AttachmentUtils - HTTP文件下载防止中文乱码 FastDFSUtils - 操作FastDFS的工具类 FtpUtils - 操作FTP的工具类(基于sun自家的包,jdk7以后不建议使用) FtpUtilsApache - 基于apache操作FTP的工具类 HttpUtils - 发送HTTP请求 IpUtils - 获取IP SFtpUtils - 操作SFTP的工具类 prop PropertiesUtils - 操作properties配置文件
### 常用 Java 第三方工具类推荐 #### Apache Commons IO Utils `org.apache.commons.io.IOUtils` 是处理输入输出流的强大工具类之一。该工具类提供了许多静态方法来简化文件读写操作以及资源关闭等常见任务[^1]。 ```java import org.apache.commons.io.IOUtils; // 示例:复制InputStream到OutputStream并自动关闭两者 IOUtils.copy(inputStream, outputStream); ``` #### Apache Commons Lang StringUtils 来自 `org.apache.commons.lang3` 的 `StringUtils` 提供了一系列用于字符串处理的方法,比如去除空白字符、判断字符串是否为空或仅含空格等功能[^3]。 ```java import org.apache.commons.lang3.StringUtils; public class Example { public static void main(String[] args) { boolean isEmpty = StringUtils.isEmpty(null); // true String trimmed = StringUtils.trimToEmpty(" hello world "); // "hello world" } } ``` #### JSON 处理库 Jackson 或 Gson 对于JSON序列化/反序列化的场景下,Jackson 和 Google 的Gson都是非常流行的解决方案。它们能够轻松地把对象转换成JSON格式的数据,并支持复杂的嵌套结构。 ```json // Maven dependency for Jackson <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0</version> </dependency> // 使用Jackson进行简单的POJO与JSON互转 ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(jsonInString, User.class); String jsonResult = mapper.writeValueAsString(user); ``` #### HTTP 请求客户端 HttpClient / OkHttp 当涉及到网络请求时,Apache HttpComponents下的HttpClient或是Square公司的OkHttp都是不错的选择。这些库可以帮助开发者更方便快捷地发起HTTP(S)请求并获取响应结果。 ```xml <!-- Maven dependency for OkHttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.3</version> </dependency> ``` ```java OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.github.com") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qinxun2008081

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值