Hutool有哪些常用方法

  • Hutool是一个Java工具类库,它提供了很多方便的方法来简化Java开发。以下是一些Hutool的常用方法及其示例:

一、日期时间处理

  • DateUtil.format(Date date, String pattern): 格式化日期。
java 复制代码
// 代码如下
Date date = new Date();
String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");

二、文件操作


  • FileUtil.writeBytes(String filePath, byte[] data): 将字节数据写入文件。
java 复制代码
// 代码如下
String filePath = "example.txt";
byte[] data = "Hello, Hutool!".getBytes();
FileUtil.writeBytes(filePath, data);

三、字符串处理


  • StrUtil.startWith(CharSequence str, CharSequence prefix): 检查字符串是否以指定前缀开始。
java 复制代码
// 代码如下
String str = "Hello World";
boolean startsWith = StrUtil.startWith(str, "Hello");

四、JSON处理


  • JsonUtil.getJson().toJson(Object object): 将Java对象转换为JSON字符串。
java 复制代码
// 代码如下
Map<String, Object> map = new HashMap<>();
map.put("name", "Hutool");
String jsonString = JsonUtil.getJson().toJson(map);

五、加密解密


  • SecureUtil.md5(byte[] data): 对字节数据进行MD5加密。
java 复制代码
// 代码如下
String data = "Hutool";
byte[] bytes = data.getBytes();
String md5 = SecureUtil.md5(bytes);

六、网络请求


  • HttpRequest.get(String url): 发送HTTP GET请求。
java 复制代码
// 代码如下
String url = "http://example.com/api/data";
HttpRequest.get(url).execute().body();

七、图片处理


  • ImgUtil.read(String filePath): 读取图片文件。
java 复制代码
// 代码如下
String filePath = "image.png";
Image image = ImgUtil.read(filePath);

八、验证码生成

  • CaptchaUtil.createMathCaptcha(int width, int height): 生成数学运算验证码。
java 复制代码
Captcha captcha = CaptchaUtil.createMathCaptcha(200, 100);

九、Bean操作

  • BeanUtil.copyProperties(Object source, Object target): 将一个对象的属性复制到另一个对象。
java 复制代码
User source = new User("Hutool", 30);
UserDTO target = new UserDTO();
BeanUtil.copyProperties(source, target);

十、系统信息

  • SystemUtil.getOsInfo(): 获取操作系统信息。
java 复制代码
String osInfo = SystemUtil.getOsInfo();

十一、Excel处理

  • ExcelUtil.getReader(String filePath): 读取Excel文件。
java 复制代码
String filePath = "example.xlsx";
ExcelReader reader = ExcelUtil.getReader(filePath);

十二、二维码生成

  • QrCodeUtil.createText(String content, int width, int height): 生成文本内容的二维码。
java 复制代码
String content = "http://hutool.cn";
QrCodeUtil.createText(content, 300, 300, "qrcode.png");

十三、邮件发送

  • MailUtil.send(String to, String subject, String content, String... cc): 发送邮件
java 复制代码
String to = "[email protected]";
String subject = "Test Mail";
String content = "Hello, Hutool!";
MailUtil.send(to, subject, content);

十四、验证码图片生成

  • CaptchaUtil.createCharCaptcha(int width, int height): 生成字符验证码图片。
java 复制代码
Captcha captcha = CaptchaUtil.createCharCaptcha(200, 100);

十五、反射操作

  • ReflectUtil.invokeMethod(Object instance, String methodName, Object... params): 调用对象的指定方法。
java 复制代码
Object instance = new MyClass();
Object result = ReflectUtil.invokeMethod(instance, "myMethod", "arg1", 123);

十六、线程池管理

  • ThreadPoolUtil.getExecutor(): 获取默认的线程池。
java 复制代码
ExecutorService executor = ThreadPoolUtil.getExecutor();
executor.submit(() -> {
    // Task code here
});

十七、Bean拷贝

  • BeanUtil.copyProperties(Object source, Class<?> clazz): 将源对象的属性拷贝到指定类型的新对象。
java 复制代码
User source = new User("Hutool", 30);
UserDTO target = BeanUtil.copyProperties(source, UserDTO.class);

十八、正则表达式

  • RegexUtil.isMatch(CharSequence str, String regex): 检查字符串是否与正则表达式匹配。
java 复制代码
String str = "Hello123";
boolean isMatch = RegexUtil.isMatch(str, "^[a-zA-Z]+[0-9]+$");

十九、Bean验证

  • ValidUtil.isEmail(CharSequence email): 验证邮箱地址是否有效。
java 复制代码
String email = "[email protected]";
boolean isValid = ValidUtil.isEmail(email);

二十、网络工具

  • NetUtil.getHostIp(): 获取本机的IP地址。
java 复制代码
String hostIp = NetUtil.getHostIp();

二十一、URL处理

  • UrlUtil.decode(String str, String charset): 对URL进行解码。
java 复制代码
String encodedUrl = "http%3A%2F%2Fexample.com";
String decodedUrl = UrlUtil.decode(encodedUrl, StandardCharsets.UTF_8);

二十二、集合操作

  • CollUtil.newArrayList(): 创建一个新的ArrayList。
java 复制代码
List<String> list = CollUtil.newArrayList("Hutool", "Java", "Tools");

二十三、随机数生成

  • RandomUtil.randomInt(int min, int max): 生成指定范围内的随机整数。
java 复制代码
int randomInt = RandomUtil.randomInt(1, 100);

二十四、日志工具

  • LogUtil.get(): 获取日志对象。
java 复制代码
Logger logger = LogUtil.get();
logger.info("Hello, Hutool!");

二十五、配置文件处理

  • Setting.getSetting(String filePath): 加载配置文件。
java 复制代码
String filePath = "config.properties";
Setting setting = Setting.getSetting(filePath);
String value = setting.getByPath("key");

二十六、压缩解压

  • ZipUtil.zip(String path, String destPath): 将文件夹或文件压缩为ZIP格式。
java 复制代码
String path = "/path/to/directory";
String destPath = "/path/to/archive.zip";
ZipUtil.zip(path, destPath);

二十七、HTTP客户端

  • HttpRequest.post(...).body(...).execute(): 发送HTTP POST请求并获取响应。
java 复制代码
String url = "http://example.com/api/data";
HttpRequest request = HttpRequest.post(url)
    .header(Header.USER_AGENT, "Hutool http client")
    .body("key1=value1&key2=value2");
HttpResponse response = request.execute();
String body = response.body();

二十八、FTP客户端

  • Ftp.getFtp(String host, int port, String username, String password): 创建FTP客户端连接。
java 复制代码
String host = "ftp.example.com";
int port = 21;
String username = "user";
String password = "password";
Ftp ftp = Ftp.getFtp(host, port, username, password);
ftp.connect();
ftp.upload("local/path/file.txt", "remote/path/file.txt");
ftp.close();

二十九、模板引擎

  • TemplateUtil.createTemplate(String resourcePath): 创建模板引擎实例。
java 复制代码
String resourcePath = "/templates/template.ftl";
Template template = TemplateUtil.createTemplate(resourcePath);
Map<String, Object> model = new HashMap<>();
model.put("name", "Hutool");
String result = template.render(model);

三十、图像裁剪

  • ImgUtil.crop(BufferedImage src, int x, int y, int width, int height): 裁剪图像。
java 复制代码
String imgPath = "/path/to/image.png";
BufferedImage src = ImgUtil.read(imgPath);
BufferedImage croppedImg = ImgUtil.crop(src, 100, 100, 200, 200);
ImgUtil.write(croppedImg, "/path/to/cropped_image.png");

三十一、图像水印

  • ImgUtil.pressText(BufferedImage src, String pressText, Font font, Color color): 在图像上添加文字水印。
java 复制代码
String imgPath = "/path/to/image.png";
BufferedImage src = ImgUtil.read(imgPath);
Font font = new Font("宋体", Font.BOLD, 60);
Color color = Color.RED;
ImgUtil.pressText(src, "Hutool", font, color, 10, 10);
ImgUtil.write(src, "/path/to/watermarked_image.png");

三十二、图像缩放

  • ImgUtil.zoom(BufferedImage src, double scaleWidth, double scaleHeight): 缩放图像。
java 复制代码
String imgPath = "/path/to/image.png";
BufferedImage src = ImgUtil.read(imgPath);
BufferedImage zoomedImg = ImgUtil.zoom(src, 0.5, 0.5);
ImgUtil.write(zoomedImg, "/path/to/zoomed_image.png");

三十三、图像旋转

  • ImgUtil.rotate(BufferedImage src, float degree): 旋转图像。
java 复制代码
String imgPath = "/path/to/image.png";
BufferedImage src = ImgUtil.read(imgPath);
BufferedImage rotatedImg = ImgUtil.rotate(src, 90);
ImgUtil.write(rotatedImg, "/path/to/rotated_image.png");

三十四、文件类型检测

  • FileTypeUtil.guessFileType(String filePath): 检测文件类型。
java 复制代码
String filePath = "/path/to/file";
FileType fileType = FileTypeUtil.guessFileType(filePath);

三十五、UUID生成

  • IdUtil.randomUUID(): 生成一个随机的UUID。
java 复制代码
String uuid = IdUtil.randomUUID();

三十六、分页

  • Page.of(int pageIndex, int pageSize, long total): 创建分页对象。
java 复制代码
int pageIndex = 1;
int pageSize = 10;
long total = 100;
Page page = Page.of(pageIndex, pageSize, total);

三十七、服务端配置

  • ServerUtil.getServerPort(): 获取当前服务的端口号。
java 复制代码
int port = ServerUtil.getServerPort();

三十八、服务端信息

  • ServerUtil.servletPath(): 获取Servlet路径。
java 复制代码
String servletPath = ServerUtil.servletPath();

三十九、服务端上下文

  • ContextUtil.getRealPath(String path): 获取Web应用的真实路径。
java 复制代码
String realPath = ContextUtil.getRealPath("/path/to/resource");

四十、服务端请求

  • RequestUtil.getClientIP(HttpServletRequest request): 获取客户端IP地址。
java 复制代码
HttpServletRequest request = ...; // Assume this is obtained from the servlet
String clientIP = RequestUtil.getClientIP(request);

四十一、服务端响应

  • ResponseUtil.renderJson(HttpServletRequest request, HttpServletResponse response, Object data): 发送JSON响应。''
java 复制代码
HttpServletResponse response = ...; // Assume this is obtained from the servlet
Map<String, Object> data = new HashMap<>();
data.put("status", "success");
ResponseUtil.renderJson(null, response, data);

四十二、服务端会话

  • SessionUtil.getSession(): 获取当前会话。
java 复制代码
Session session = SessionUtil.getSession();

四十三、服务端Cookie

  • CookieUtil.setCookie(HttpServletResponse response, String name, String value, int maxAge): 设置Cookie。
java 复制代码
HttpServletResponse response = ...; // Assume this is obtained from the servlet
CookieUtil.setCookie(response, "username", "hutool", 3600);
  • 这些示例提供了对Hutool库中不同功能的基本理解。Hutool的每个工具类都提供了丰富的静态方法,以简化Java开发中的各种常见任务。
相关推荐
ApiHug14 小时前
ApiHug 1.3.9 支持 Spring 3.5.0 + Plugin 0.7.4 内置小插件升级!儿童节快乐!!!
java·后端·spring·api·apihug·apismart
webmote332 天前
DeepSeek私域数据训练之封装Anything LLM的API 【net 9】
.net·api·deepseek
慧都小妮子2 天前
跨平台浏览器集成库JxBrowser 支持 Chrome 扩展程序,高效赋能 Java 桌面应用
开发语言·python·api·jxbrowser·chrome 扩展程序
Web极客码3 天前
WordPress 6.5版本带来的新功能
前端·api·wordpress
天才在此4 天前
开源库免费API服务平台 ALLBEAPI
开源·api·免费
Estar.Lee6 天前
腾讯云开发者社区文章内容提取免费API接口教程
android·云计算·腾讯云·api·免费api·api大全
dearxue7 天前
ApiHug 1.3.9 支持 Spring 3.5.0 + Plugin 0.7.4 内置小插件升级 & 儿童节快乐!
spring·api·intellij idea
PPIO派欧云7 天前
PPIO私有化部署模板上新!10分钟拥有专属最新DeepSeek模型
llm·aigc·api
POLOAPI7 天前
Anthropic Claude 4 深度解析:从模型特性到POLOAPI接入开发实践
api·claude
PPIO派欧云8 天前
首发!PPIO派欧云上线DeepSeek-R1-0528-Qwen3-8B蒸馏模型
人工智能·开源·api·deepseek