当前位置 : 首页 » 文章分类 :  开发  »  Hutool

Hutool

Hutool

https://hutool.cn/

https://github.com/dromara/hutool/


DateUtil

formatDateTime() 格式化日期

格式 yyyy-MM-dd HH:mm:ss

parse() 解析日期字符串

public static DateTime parse(CharSequence dateCharSequence) 支持几乎所有格式

yyyy-MM-dd HH:mm:ss
yyyy/MM/dd HH:mm:ss
yyyy.MM.dd HH:mm:ss
yyyy年MM月dd日 HH时mm分ss秒
yyyy-MM-dd
yyyy/MM/dd
yyyy.MM.dd
HH:mm:ss
HH时mm分ss秒
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss.SSSSSS
yyyyMMddHHmmss
yyyyMMddHHmmssSSS
yyyyMMdd
EEE, dd MMM yyyy HH:mm:ss z
EEE MMM dd HH:mm:ss zzz yyyy
yyyy-MM-dd'T'HH:mm:ss'Z'
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
yyyy-MM-dd'T'HH:mm:ssZ
yyyy-MM-dd'T'HH:mm:ss.SSSZ

offset/offsetSecond/offsetDay 日期时间加减

public static DateTime offset(Date date, DateField dateField, int offset)
public static DateTime offsetSecond(Date date, int offset)
public static DateTime offsetDay(Date date, int offset)

between/betweenMs 计算时间差

public static long between(Date beginDate, Date endDate, DateUnit unit)
public static long betweenMs(Date beginDate, Date endDate)

formatBetween() 格式化时间段

XX天XX小时XX分XX秒XX毫秒

public static String formatBetween(Date beginDate, Date endDate)
public static String formatBetween(long betweenMs)

beginOfDay/endOfDay 一天的开始/结束时间

public static DateTime beginOfDay(Date date)
public static DateTime endOfDay(Date date)


DatePattern

NORM_DATETIME_FORMAT

// yyyyMMddHHmmss
PURE_DATETIME_FORMAT.format(new Date())

createFormatter

DatePattern.createFormatter(“MMdd”).format(LocalDateTime.now())


CharPool 字符池

SLASH 斜杠


StrPool 字符串池

DOT 点

COMMA 逗号

UNDERLINE 下划线

C_LF ‘\n’换行

LF “\n”换行

DOUBLE_QUOTES 双引号


StrUtil

NULL 字符串常量”null”

public static final String NULL = “null”;

cleanBlank() 删除空白


Convert

convert(type, value) 类型转换

chineseToNumber 中文转数字

一百一十二 -> 112
一千零一十二 -> 1012

含中文数字的字符串排序

基于 chineseToNumber 实现含中文数字的字符串 转 阿拉伯数字,用于排序

private static final Pattern PATTERN = Pattern.compile("([零一二三四五六七八九十百千万亿]+)");

/**
 * 包含中文数字的字符串转数字,第十五条 -> 15
 * @param str
 * @return
 */
public static long chineseToNumber(String str) {
    Matcher matcher = PATTERN.matcher(str);
    if (matcher.find()) {
        return Convert.chineseToNumber(matcher.group(1));
    }
    return 0;
}

@Test
public void test() {
    List<String> list = Arrays.asList("第三十章", "XX二百三十局", "第一编", "最后一千零二个", "一千零一夜");
    list.sort(Comparator.comparing(ChineseNumberTest::chineseToNumber));
    for (String str : list) {
        System.out.println(str);
    }
}

结果:

第一编
第三十章
XX二百三十局
一千零一夜
最后一千零二个

SpringUtil

getBeansOfType() 从Spring上下文获取指定类型的Bean

hutool-all 包的 spring.factories 中启用了 SpringUtil 自动配置,可无需注入直接使用 SpringUtil.getBean


ThreadUtil

sleep() 当前线程sleep

createThreadFactory() 指定前缀创建线程工厂


HttpUtil

get() GET请求


URLUtil

encode()

java.net.URLEncoder 会把所有特殊字符包括:和/都编码,带中文的连接编码后无法访问。
cn.hutool.core.util.URLUtil.encode() 可实现只编码中文和空格,不编码 http://


FileUtil

exist(str/File) 判断文件(夹)是否存在

del(str/File) 删除文件(夹)

writeFromStream() 输入流写入文件

public static File writeFromStream(InputStream in, File dest) throws IORuntimeException
public static File writeFromStream(InputStream in, String fullFilePath) throws IORuntimeException

ZipUtil

zip() 压缩

unzip() 解压


RuntimeUtil


CollectionUtil/CollUtil

distinct() 集合按指定字段去重

public static <T, K> List<T> distinct(Collection<T> collection, Function<T, K> uniqueGenerator, boolean override)
override=true 有重复时保留后面的,删除前面的
override=false 有重复时保留前面的,删除后面的

例如 users 列表按 name 去重

List<User> users = CollectionUtil.distinct(users, User::getName, true);

reverse()/reverseNew() 反转列表

public static <T> List<T> reverse(List<T> list) // 反序给定List,会在原List基础上直接修改
public static <T> List<T> reverseNew(List<T> list) // 反序给定List,会创建一个新的List,原List数据不变

IdUtil

fastSimpleUUID() 无横线的uuid


SecureUtil

md5()


SmUtil

SM2 解密

private String sm2Decrypt(String encrypted) {
    SM2 sm2 = SmUtil.sm2(sm2PrivateKey("私钥"), "公钥");
    return new String(sm2.decryptFromBcd(sm2EncryptedText(encrypted), KeyType.PrivateKey));
}

// 私钥前加00
private String sm2PrivateKey(String privateKey) {
    return "00" + privateKey;
}

// 密文前加04
private String sm2EncryptedText(String cipherText) {
    return "04" + cipherText;
}

MailUtil

1、除了 hutoo-all,还需要单独引入 mail 依赖

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

2、maven 项目 src/main/resources 中新建 mail.setting

# 发件人(必须正确,否则发送失败)
from = hutool@yeah.net
# 密码(注意,某些邮箱需要为SMTP服务单独设置密码,详情查看相关帮助)
pass = q1w2e3

3、发邮件

// 发送文本邮件
MailUtil.send("hutool@foxmail.com", "测试", "邮件来自Hutool测试", false);
// 发送html邮件
MailUtil.send("hutool@foxmail.com", "测试", "<h1>邮件来自Hutool测试</h1>", true, FileUtil.file("d:/aaa.xml"));

ExcelWriter

1、需要额外引入 POI 依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.1.0</version>
</dependency>

2、生成或写入 excel

List<String> titleRow = Lists.newArrayList("第一列", "第二列", "第三列");
List<List<String>> excelRows = Lists.newArrayList();
excelRows.add(titleRow);
try (
        InputStream inputStream = new FileInputStream(jsonlFile);
        ExcelWriter excelWriter = ExcelUtil.getWriter(excelFile) // 自动close时才真正创建并写入excel
) {
        excelRows.add(Lists.newArrayList("a", "b", "c"));
        excelWriter.write(excelRows); // 写入excel
} catch (Exception e) {
    log.error("write excel error", e);
}

PinyinUtil

使用PinyinUtil类时需要引入一个第三方的拼音库。例如pinyin4j、TinyPinyin、jpinyin,否则报错:
Caused by: cn.hutool.extra.pinyin.PinyinException: No pinyin jar found ! Please add one of it to your project !
建议 TinyPinyin https://github.com/promeG/TinyPinyin

<dependency>
    <groupId>io.github.biezhi</groupId>
    <artifactId>TinyPinyin</artifactId>
    <version>2.0.3.RELEASE</version>
</dependency>

getPinyin 生成拼音

getFirstLetter 生成拼音首字母


上一篇 H2

下一篇 JsonPath

阅读
评论
1.4k
阅读预计6分钟
创建日期 2023-08-28
修改日期 2024-04-24
类别
标签

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论