当前位置: 首页 > article >正文

Java 常用工具类大全:高频工具类及代码示例(后续继续补充)

在 Java 开发中,工具类是提高开发效率的利器。本文将总结全网搜索频率最高的 20 个 Java 工具类,并提供详细的代码示例和说明,涵盖字符串处理、集合操作、日期时间、文件操作、数学计算等多个方面。


1. ​**StringUtils(Apache Commons Lang)​**

用于字符串处理的工具类。

 

java

import org.apache.commons.lang3.StringUtils;

public class StringUtilsExample {
    public static void main(String[] args) {
        // 判断字符串是否为空
        System.out.println(StringUtils.isEmpty("")); // true
        // 判断字符串是否为空白
        System.out.println(StringUtils.isBlank("  ")); // true
        // 反转字符串
        System.out.println(StringUtils.reverse("hello")); // olleh
    }
}

2. ​**CollectionUtils(Apache Commons Collections)​**

用于集合操作的工具类。

 

java

import org.apache.commons.collections4.CollectionUtils;

import java.util.Arrays;
import java.util.List;

public class CollectionUtilsExample {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("a", "b", "c");
        List<String> list2 = Arrays.asList("b", "c", "d");

        // 判断集合是否为空
        System.out.println(CollectionUtils.isEmpty(list1)); // false
        // 求交集
        System.out.println(CollectionUtils.intersection(list1, list2)); // [b, c]
    }
}

3. ​**DateUtils(Apache Commons Lang)​**

用于日期时间处理的工具类。

 

java

import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;

public class DateUtilsExample {
    public static void main(String[] args) {
        Date now = new Date();
        // 添加天数
        Date future = DateUtils.addDays(now, 7);
        System.out.println(future);
        // 判断是否为同一天
        System.out.println(DateUtils.isSameDay(now, future)); // false
    }
}

4. ​**FileUtils(Apache Commons IO)​**

用于文件操作的工具类。

 

java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class FileUtilsExample {
    public static void main(String[] args) throws IOException {
        // 复制文件
        FileUtils.copyFile(new File("source.txt"), new File("target.txt"));
        // 读取文件内容
        String content = FileUtils.readFileToString(new File("source.txt"), "UTF-8");
        System.out.println(content);
    }
}

5. ​**MathUtils(自定义)​**

用于数学计算的工具类。

 

java

public class MathUtils {
    // 计算两个数的最大公约数
    public static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    // 计算两个数的最小公倍数
    public static int lcm(int a, int b) {
        return a * b / gcd(a, b);
    }

    public static void main(String[] args) {
        System.out.println(gcd(12, 18)); // 6
        System.out.println(lcm(12, 18)); // 36
    }
}

6. ​**IOUtils(Apache Commons IO)​**

用于 I/O 操作的工具类。

 

java

import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;
import java.io.IOException;

public class IOUtilsExample {
    public static void main(String[] args) throws IOException {
        // 读取文件内容
        String content = IOUtils.toString(new FileInputStream("source.txt"), "UTF-8");
        System.out.println(content);
    }
}

7. ​**JsonUtils(Jackson)​**

用于 JSON 处理的工具类。

 

java

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonUtils {
    private static final ObjectMapper mapper = new ObjectMapper();

    // 将对象转换为 JSON 字符串
    public static String toJson(Object obj) throws IOException {
        return mapper.writeValueAsString(obj);
    }

    // 将 JSON 字符串转换为对象
    public static <T> T fromJson(String json, Class<T> clazz) throws IOException {
        return mapper.readValue(json, clazz);
    }

    public static void main(String[] args) throws IOException {
        String json = "{\"name\":\"John\",\"age\":30}";
        Person person = fromJson(json, Person.class);
        System.out.println(person.getName()); // John
    }
}

class Person {
    private String name;
    private int age;

    // getters and setters
}

8. ​**ReflectionUtils(Spring Framework)​**

用于反射操作的工具类。

 

java

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

public class ReflectionUtilsExample {
    public static void main(String[] args) {
        Method method = ReflectionUtils.findMethod(String.class, "length");
        System.out.println(method.getName()); // length
    }
}

9. ​**RandomUtils(Apache Commons Lang)​**

用于生成随机数的工具类。

 

java

import org.apache.commons.lang3.RandomUtils;

public class RandomUtilsExample {
    public static void main(String[] args) {
        // 生成随机整数
        int randomInt = RandomUtils.nextInt(1, 100);
        System.out.println(randomInt);
    }
}

10. ​**StopWatch(Spring Framework)​**

用于计时操作的工具类。

 

java

import org.springframework.util.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) throws InterruptedException {
        StopWatch watch = new StopWatch();
        watch.start();
        Thread.sleep(1000);
        watch.stop();
        System.out.println(watch.getTotalTimeMillis()); // 1000
    }
}

11. ​**StringJoiner(Java 8+)​**

用于拼接字符串的工具类。

 

java

import java.util.StringJoiner;

public class StringJoinerExample {
    public static void main(String[] args) {
        StringJoiner joiner = new StringJoiner(", ", "[", "]");
        joiner.add("a").add("b").add("c");
        System.out.println(joiner.toString()); // [a, b, c]
    }
}

12. ​**Optional(Java 8+)​**

用于处理空值的工具类。

 

java

import java.util.Optional;

public class OptionalExample {
    public static void main(String[] args) {
        Optional<String> optional = Optional.ofNullable(null);
        System.out.println(optional.orElse("default")); // default
    }
}

13. ​**Objects(Java 7+)​**

用于对象操作的工具类。

 

java

import java.util.Objects;

public class ObjectsExample {
    public static void main(String[] args) {
        String str = null;
        System.out.println(Objects.isNull(str)); // true
    }
}

14. ​**Arrays(Java 标准库)​**

用于数组操作的工具类。

 

java

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] arr = {3, 1, 2};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr)); // [1, 2, 3]
    }
}

15. ​**Collections(Java 标准库)​**

用于集合操作的工具类。

 

java

import java.util.Collections;
import java.util.List;

public class CollectionsExample {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("a", "b", "c");
        Collections.reverse(list);
        System.out.println(list); // [c, b, a]
    }
}

16. ​**Files(Java 7+)​**

用于文件操作的工具类。

 

java

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class FilesExample {
    public static void main(String[] args) throws IOException {
        // 读取文件内容
        String content = new String(Files.readAllBytes(Paths.get("source.txt")));
        System.out.println(content);
    }
}

17. ​**Path(Java 7+)​**

用于路径操作的工具类。

 

java

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathExample {
    public static void main(String[] args) {
        Path path = Paths.get("source.txt");
        System.out.println(path.getFileName()); // source.txt
    }
}

18. ​**Stream(Java 8+)​**

用于流式操作的工具类。

 

java

import java.util.stream.Stream;

public class StreamExample {
    public static void main(String[] args) {
        Stream.of("a", "b", "c").forEach(System.out::println); // a b c
    }
}

19. ​**DateTimeFormatter(Java 8+)​**

用于日期时间格式化的工具类。

 

java

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(now.format(formatter)); // 2023-10-01 12:34:56
    }
}

20. ​**Properties(Java 标准库)​**

用于读取配置文件的工具类。

 

java

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {
    public static void main(String[] args) throws IOException {
        Properties props = new Properties();
        props.load(new FileInputStream("config.properties"));
        System.out.println(props.getProperty("key")); // value
    }
}

http://www.kler.cn/a/589055.html

相关文章:

  • 区块链与去中心化技术
  • 基于SpringBoot的公司财务管理系统+LW示例参考
  • 工作记录 2017-01-06
  • N皇后问题——dfs解法(回溯+减枝+深搜)
  • 7、基于osg引擎实现读取vtk数据通过着色器实现简单体渲染(1)
  • go 安装swagger
  • 1.Qt SDK 的下载和安装
  • matlab 三维桥式起重机系统数学模型
  • 2025高频面试算法总结篇【递归回溯动态规划】
  • windows 下用docker 部署nginx
  • unity基础——Navigation导航系统
  • 网络安全设备系统集成方案 系统集成和网络安全
  • 命令行参数和环境变量【Linux操作系统】
  • 【论文笔记】Best Practices and Lessons Learned on Synthetic Data for Language Models
  • BigEvent项目后端学习笔记(一)用户管理模块 | 注册登录与用户信息全流程解析(含优化)
  • 数据增强常见问题与解决方案:提升AI模型性能的关键技巧
  • PyCharm如何有效地添加源与库?
  • CSS中固定定位
  • 错误记录: git 无法连接到github
  • Apache Pol (excel)