1. 程式人生 > 其它 >hutool-all 工具包

hutool-all 工具包

引入Hutool

在專案中可以通過maven引入Hutool庫,方式如下:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.6.5</version>
</dependency>
Hutool是國內程式設計師在工作中總結和積累而成的一套小而全的工具類庫,相比於谷歌高大上的工具包Guava,它更符合國內開發者的需求。
Hutool的定位是減少程式碼搜尋成本,避免從網路上覆制修改程式碼導致的潛在問題。 所有的類都有自己的使用場景。應該多讀使用文件,看這些工具是否符合自己的使用場景。 本文僅列舉了部分常用api,整個工具包的內容非常廣泛。如有需要,可到官網進一步深入學習。

Hutool的思維導圖

下面列舉一些常用的api,僅供參考。

1.1 日期時間處理

日期操作的亮點是可以通過ChineseDate類將公曆日期轉換為農曆日期。此外,使用DateUtil可以很方便的操作Date型別資料,LocalDateTimeUtil則用於操作LocalDateTime型別資料。

// 獲取年份
int year = DateUtil.year(new Date());

// 獲取今天日期 yyyy-MM-dd格式
String today = DateUtil.today();

// 獲取生肖
String chineseZodiac = DateUtil.getChineseZodiac(1990);

// 將毫秒轉成方便閱讀的時間,如3小時25分23秒232毫秒 String readableTime = DateUtil.formatBetween(12323232); // 轉為農曆日期 ChineseDate chineseDate = new ChineseDate(new Date()); // 農曆年份,如2021 final int chineseYear = chineseDate.getChineseYear(); // 農曆月份,如臘月 final String chineseMonthName = chineseDate.getChineseMonthName(); // 農曆日期,如初三
final String chineseDay = chineseDate.getChineseDay(); // 方便地將Date轉換為LocalDateTime final LocalDateTime localDateTime = LocalDateTimeUtil.of(new Date()); // 獲取一天開始時間 LocalDateTimeUtil.beginOfDay(localDateTime); // 獲取一天結束時間 LocalDateTimeUtil.endOfDay(localDateTime);

1.2 I/O

IoUtils可以方便地複製檔案,其他相關api建議使用jdk的Files工具類。

// 從檔案中獲取緩衝流
BufferedInputStream in = FileUtil.getInputStream("d:/test.txt");
BufferedOutputStream out = FileUtil.getOutputStream("d:/test2.txt");

// 拷貝檔案
IoUtil.copy(in, out);

1.3 字串處理

一些簡單易用的字串處理api,以及正則表示式的api。

// 判斷字串是否為null或空串
boolean isEmpty = StrUtil.isEmpty(str);

// 判斷字串是否為null或空串或空白字元
boolean isBlank = StrUtil.isBlank(str);

// 將字串用指定字元填充到指定長度
String filled = StrUtil.fillAfter(str, '*', 10);

// 填充字串模板
String format = StrUtil.format("a的值為{a}, b的值為{b}", Map.of("a", "aValue", "b", "bValue"));

// 判斷字串是否為中文字串
boolean match = ReUtil.isMatch(ReUtil.RE_CHINESES, "中國人");

1.4 集合框架

可以用於建立集合和集合的交、並、差集操作。

// 新建一個HashSet
Set<Integer> hashSet = CollUtil.newHashSet(1, 2, 3);
Set<Integer> linkedHashSet = CollUtil.newLinkedHashSet(4, 2, 3);

// 兩個集合取交集
Collection<Integer> intersection = CollUtil.intersection(hashSet, linkedHashSet);

// 兩個集合取並集
Collection<Integer> union = CollUtil.union(hashSet, linkedHashSet);

// 兩個集合取差集
Collection<Integer> disjunction = CollUtil.disjunction(hashSet, linkedHashSet);

// 判斷一個集合是否為null或空集
boolean empty = CollUtil.isEmpty(hashSet);

// 建立一個ArrayList
List<Integer> arrayList = ListUtil.toList(1, 2, 3);

// 建立一個LinkedList
List<Integer> linkedList = ListUtil.toLinkedList(1, 2, 3);

// 建立一個map
Map<String, Object> map = MapUtil.<String, Object>builder().put("a", 1).put("b", 2).build();

1.5 常見業務

身份證、社會信用程式碼、拼音操作、生成二維碼、生成唯一ID等一些常見業務場景api。

// 根據身份證號獲取出生日期
String birth = IdcardUtil.getBirthByIdCard(idCard);

// 根據身份證號獲取省份
String province = IdcardUtil.getProvinceByIdCard(idCard);

// 判斷身份證號是否合法
boolean valid = IdcardUtil.isValidCard18(idCard);

// 獲取一個隨機的社會信用程式碼
String creditCode = CreditCodeUtil.randomCreditCode();

// 判斷社會信用程式碼是否合法
boolean isCreditCode = CreditCodeUtil.isCreditCode(creditCode);

// 將漢字轉為拼音,需要引入TinyPinyin、JPinyin或Pinyin4j的jar包
String china = PinyinUtil.getPinyin("中國");

// 將字串生成為二維碼,需要引入com.google.zxing.core的jar包
BufferedImage qrCodeImage = QrCodeUtil.generate("www.baidu.com", QrConfig.create());
ImageIO.write(qrCodeImage, "png", new File("a.png"));

// 生成uuid
String uuid = IdUtil.fastSimpleUUID();

// 建立基於Twitter SnowFlake演算法的唯一ID,適用於分散式系統
final Snowflake snowflake = IdUtil.createSnowflake(1, 1);
final long id = snowflake.nextId();

2. 定時任務

通過簡單的api,實現全域性統一的定時任務排程

// 新增新的定時任務
final String scheduleId = CronUtil.schedule("*/2 * * * * *", (Task) () -> System.out.println("執行定時任務"));

// 設定是否支援秒級別定時任務
CronUtil.setMatchSecond(true);

// 開啟定時任務
CronUtil.start();

3. 驗證碼

可以方便地生成圖形驗證碼。

// 生成線段干擾的驗證碼
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 5, 3);
lineCaptcha.write("/your/path/b.png");

// 生成圓圈干擾的驗證碼
CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
captcha.write("/your/path/c.png");

// 生成扭曲干擾的驗證碼
ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
shearCaptcha.write("/your/path/d.png");

4. 快取

可以方便地使用基於記憶體的快取,並設定過期時間的策略。

// 建立先進先出的快取,並設定過期時間
FIFOCache<String, Object> cache = CacheUtil.newFIFOCache(1000, 3600 * 1000);

// 向快取中新增元素
cache.put("a", 1);

// 從快取中讀取元素
cache.get("a");

5. Excel操作

// 將檔案轉換為ExcelReader
ExcelReader reader = ExcelUtil.getReader("d:/aaa.xlsx");

// 讀取所有行和列的資料
List<List<Object>> data = reader.read();

// 讀取為Map列表,預設excel第一行為標題行,Map中的key為標題,value為標題對應的單元格值。
List<Map<String,Object>> dataMap = reader.readAll();

//建立writer
ExcelWriter writer = ExcelUtil.getWriter("d:/bbb.xlsx");

// 資料量特別大時,使用BigExcelWriter物件,可以避免記憶體溢位
ExcelWriter bigWriter = ExcelUtil.getBigWriter("d:/bbb.xlsx");

// 構造資料
List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd");
List<String> row2 = CollUtil.newArrayList("aa1", "bb1", "cc1", "dd1");
List<String> row3 = CollUtil.newArrayList("aa2", "bb2", "cc2", "dd2");
List<String> row4 = CollUtil.newArrayList("aa3", "bb3", "cc3", "dd3");
List<String> row5 = CollUtil.newArrayList("aa4", "bb4", "cc4", "dd4");
List<List<String>> rows = CollUtil.newArrayList(row1, row2, row3, row4, row5);

// 一次性將資料寫入excel中
writer.write(rows, true);

6. Http請求

Map<String, Object> params = MapUtil.<String, Object>builder().put("a", 1).build();
// 傳送get請求
String getResult = HttpUtil.get("https://www.baidu.com", params);

// 傳送post請求
String postResult = HttpUtil.post("https://www.baidu.com", params);

// 以application/json方式傳送post請求
String jsonPostResult = HttpUtil.post("https://www.baidu.com", JSON.toJSONString(params));

// 下載檔案,提供生命週期鉤子
HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"), new StreamProgress() {
    @Override
    public void start() {
        System.out.println("開始下載");
    }

    @Override
    public void progress(long progressSize) {
        System.out.println("下載中,已下載" + FileUtil.readableFileSize(progressSize));
    }

    @Override
    public void finish() {
        System.out.println("下載完成");
    }
});

7. 加密

7.1 加密和解密

// md5摘要加密
String md5 = SecureUtil.md5("abc");

// sha1摘要加密
String sha1 = SecureUtil.sha1("abc");

// 生成非對稱金鑰對
KeyPair keyPair = SecureUtil.generateKeyPair("RSA");
String publicKey = Base64Encoder.encode(keyPair.getPublic().getEncoded());
String privateKey = Base64Encoder.encode(keyPair.getPrivate().getEncoded());

// 利用公鑰加密
String encryptBase64 = SecureUtil.rsa(privateKey, publicKey).encryptBase64("abc", KeyType.PublicKey);

// 利用私鑰解密
String decrypt = new String(SecureUtil.rsa(privateKey, publicKey).decrypt(encryptBase64, KeyType.PrivateKey));

7.2 簽名和驗籤

// 建立簽名物件
Sign sign = SecureUtil.sign(SignAlgorithm.MD5withRSA);

// 生成簽名
final byte[] bytes = "abc".getBytes();
byte[] signed = sign.sign(bytes);

// 驗證簽名
boolean verify = sign.verify(bytes, signed);
System.out.println(verify);