Hutool——國產良心工具包, 加密,身份證處理


 pom.xml

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

上次我們分享了谷歌高大上的工具包Guava,這次我們來分享一款更接地氣的國產工具包Hutool。

Hutool是國內程序員在工作中總結和積累而成的一套小而全的工具類庫,相比於Guava,它更符合國內開發者的需求。

Hutool首次發布於2014年,最新版本為5.6.5,到目前為止已經在github上收獲了1.9萬個贊。

我們還是先來看一下學習Hutool的思維導圖。

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

1. 基礎工具

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);

8. 其他說明

8.1 引入Hutool

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

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

8.2 注意事項

  1. Hutool的定位是減少代碼搜索成本,避免從網絡上復制修改代碼導致的潛在問題。
  2. 所有的類都有自己的使用場景,沒有銀彈。應該多讀使用文檔,看這些工具是否符合自己的使用場景。
  3. 本文僅列舉了部分常用api,整個工具包的內容非常廣泛。如有需要,可到官網進一步深入學習。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM