在 Java 开发中,工具类是提高开发效率的利器。本文将总结全网搜索频率最高的 20 个 Java 工具类,并提供详细的代码示例和说明,涵盖字符串处理、集合操作、日期时间、文件操作、数学计算等多个方面。
1. **StringUtils
(Apache Commons Lang)**
用于字符串处理的工具类。
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)**
用于集合操作的工具类。
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)**
用于日期时间处理的工具类。
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)**
用于文件操作的工具类。
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
(自定义)**
用于数学计算的工具类。
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)); // 6System.out.println(lcm(12, 18)); // 36}
}
6. **IOUtils
(Apache Commons IO)**
用于 I/O 操作的工具类。
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 处理的工具类。
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)**
用于反射操作的工具类。
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)**
用于生成随机数的工具类。
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)**
用于计时操作的工具类。
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+)**
用于拼接字符串的工具类。
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+)**
用于处理空值的工具类。
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+)**
用于对象操作的工具类。
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 标准库)**
用于数组操作的工具类。
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 标准库)**
用于集合操作的工具类。
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+)**
用于文件操作的工具类。
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+)**
用于路径操作的工具类。
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+)**
用于流式操作的工具类。
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+)**
用于日期时间格式化的工具类。
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 标准库)**
用于读取配置文件的工具类。
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}
}