Hutool工具類使用說明
Hutool是一個Java工具類庫,提供了豐富的功能模塊,包括字符串處理、日期時間操作、IO流、加密解密、HTTP客戶端等。以下是一些常用模塊的具體使用方法。
字符串工具(StrUtil)
字符串處理是開發中的常見需求,StrUtil
模塊提供了高效的字符串操作方法。
// 判斷字符串是否為空
boolean isEmpty = StrUtil.isEmpty(""); // true// 格式化字符串
String template = "姓名:{},年齡:{}";
String formatted = StrUtil.format(template, "張三", 25); // 姓名:張三,年齡:25// 截取字符串
String subStr = StrUtil.sub("Hello World", 0, 5); // "Hello"
日期時間工具(DateUtil)
DateUtil
模塊簡化了日期時間的操作,支持日期解析、格式化、計算等功能。
// 字符串轉日期
Date date = DateUtil.parse("2023-10-01");// 日期加減
Date newDate = DateUtil.offsetDay(date, 1); // 加1天// 格式化日期
String formattedDate = DateUtil.format(date, "yyyy/MM/dd"); // "2023/10/01"
文件IO工具(FileUtil)
FileUtil
模塊封裝了常見的文件操作,如讀寫、復制、刪除等。
// 讀取文件內容
String content = FileUtil.readUtf8String("test.txt");// 寫入文件
FileUtil.writeUtf8String("Hello Hutool", "output.txt");// 復制文件
FileUtil.copy("source.txt", "target.txt", true);
HTTP客戶端工具(HttpUtil)
HttpUtil
模塊提供了簡潔的HTTP請求方法,支持GET、POST等請求方式。
// GET請求
String response = HttpUtil.get("https://example.com");// POST請求
Map<String, Object> params = new HashMap<>();
params.put("name", "Hutool");
String postResponse = HttpUtil.post("https://example.com/api", params);
加密解密工具(SecureUtil)
SecureUtil
模塊支持多種加密算法,如MD5、SHA-1、AES等。
// MD5加密
String md5 = SecureUtil.md5("123456");// AES加密解密
String data = "Hello Hutool";
String key = "1234567812345678";
String encrypted = SecureUtil.aes(key.getBytes()).encryptHex(data);
String decrypted = SecureUtil.aes(key.getBytes()).decryptStr(encrypted);
集合工具(CollUtil)
CollUtil
模塊提供了集合操作的便捷方法,如判空、分組、過濾等。
List<String> list = Arrays.asList("a", "b", "c");// 集合判空
boolean isNotEmpty = CollUtil.isNotEmpty(list); // true// 分組
Map<Character, List<String>> grouped = CollUtil.groupByField(list, str -> str.charAt(0));
反射工具(ReflectUtil)
ReflectUtil
模塊簡化了Java反射操作,支持動態調用方法、訪問字段等。
// 調用方法
class TestClass {public void print(String msg) {System.out.println(msg);}
}
ReflectUtil.invoke(new TestClass(), "print", "Hello Reflection");// 訪問字段
class TestField {private String name = "Hutool";
}
String name = (String) ReflectUtil.getFieldValue(new TestField(), "name");
驗證碼工具(CaptchaUtil)
CaptchaUtil
模塊可用于生成圖形驗證碼,支持干擾線、扭曲等效果。
// 生成驗證碼
LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
String code = captcha.getCode(); // 驗證碼文本
captcha.write("captcha.png"); // 保存驗證碼圖片
BeanUtil:JavaBean操作工具
對象屬性拷貝
將源對象的屬性值拷貝到目標對象:
User srcUser = new User("張三", 25);
User targetUser = new User();
BeanUtil.copyProperties(srcUser, targetUser);
Map轉JavaBean
將Map轉換為JavaBean對象:
Map<String, Object> map = new HashMap<>();
map.put("name", "李四");
map.put("age", 30);
User user = BeanUtil.mapToBean(map, User.class, false);
復制插入
JavaBean轉Map
將JavaBean對象轉為Map:
User user = new User("王五", 28);
Map<String, Object> map = BeanUtil.beanToMap(user);
IdUtil:唯一ID生成工具
生成UUID
生成不帶連字符的UUID
String uuid = IdUtil.simpleUUID();
生成Snowflake ID
基于Snowflake算法生成分布式ID(雪花算法)
long snowflakeId = IdUtil.getSnowflake().nextId();
生成ObjectId
MongoDB風格的ObjectId:
String objectId = IdUtil.objectId();
RandomUtil:隨機數生成工具
生成隨機整數
生成指定范圍內的隨機整數:
int randomInt = RandomUtil.randomInt(1, 100);
生成隨機字符串
生成指定長度的隨機字母數字字符串(可用在隨機生成驗證碼)
String randomString = RandomUtil.randomString(10);
生成隨機UUID
生成帶連字符的標準UUID
String randomUUID = RandomUtil.randomUUID();
ZipUtil:壓縮解壓工具
壓縮文件/目錄
將文件或目錄壓縮為ZIP:
File file = new File("/path/to/file.txt");
File zipFile = ZipUtil.zip(file);
解壓ZIP文件
解壓ZIP到指定目錄:
File zipFile = new File("/path/to/archive.zip");
File destDir = new File("/path/to/output");
ZipUtil.unzip(zipFile, destDir);
壓縮到流
將文件壓縮為ZIP并輸出到:
File file = new File("/path/to/file.txt");
OutputStream out = new FileOutputStream("/path/to/output.zip");
ZipUtil.toZip(file, out);
以上方法均基于Hutool工具包的最新版本(建議使用5.8.x+)。具體使用時需確保引入依賴:
xml復制插入
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.20</version>
</dependency>