Java常用工具类
Java常用工具类
├── IO相关
│ ├── FileUtils
│ └── IOUtils
├── 集合/数组相关
│ ├── CollectionUtils
│ ├── MapUtils
│ ├── ArrayUtils
│ ├── Lists
│ └── Maps
├── 字符串相关
│ ├── StringUtils
│ └── Splitter/Joiner
├── 日期相关
│ ├── DateUtils
│ ├── DateFormatUtils
│ └── LocalDate
└── 计时
└── StopWatch
IO相关
FileUtils
提供文件操作的便捷方法,如创建、删除、复制文件或目录等
-
功能:
static File[] listFiles(File directory, String[] extensions, boolean recursive)
: 列出指定目录下的所有文件,支持扩展名过滤和递归搜索。static void copyFile(File srcFile, File destFile)
: 复制文件。static void deleteDirectory(File directory)
: 删除目录及其所有内容。static long sizeOfDirectory(File directory)
: 获取目录的大小(字节)。static void touch(File file)
: 更新文件的最后修改时间,类似于Unix的touch
命令。
-
示例:
// 列出指定目录下的所有 .txt 文件 File[] txtFiles = FileUtils.listFiles(new File("/path/to/directory"), new String[]{"txt"}, true); // 复制文件 FileUtils.copyFile(new File("source.txt"), new File("destination.txt")); // 删除目录 FileUtils.deleteDirectory(new File("/path/to/directory")); // 获取目录的大小 long directorySize = FileUtils.sizeOfDirectory(new File("/path/to/directory")); // 更新文件的最后修改时间 FileUtils.touch(new File("file.txt"));
IOUtils
提供输入输出流操作的便捷方法,如读取、关闭流等。
-
功能:
static byte[] toByteArray(InputStream input)
: 将输入流转换为字节数组。static String toString(InputStream input, Charset encoding)
: 将输入流转换为字符串。static void closeQuietly(Closeable closeable)
: 安静地关闭可关闭对象,不抛出异常。static int copy(InputStream input, OutputStream output)
: 将输入流复制到输出流。static void write(String data, Writer output, Charset encoding)
: 将字符串写入输出流。
-
示例:
// 将输入流转换为字节数组 byte[] bytes = IOUtils.toByteArray(new FileInputStream("file.txt")); // 将输入流转换为字符串 String content = IOUtils.toString(new FileInputStream("file.txt"), StandardCharsets.UTF_8); // 安静地关闭输入流 InputStream is = new FileInputStream("file.txt"); IOUtils.closeQuietly(is); // 将输入流复制到输出流 InputStream in = new FileInputStream("source.txt"); OutputStream out = new FileOutputStream("destination.txt"); IOUtils.copy(in, out); // 将字符串写入输出流 Writer writer = new FileWriter("output.txt"); IOUtils.write("Hello, World!", writer, StandardCharsets.UTF_8);
集合/数组相关
CollectionUtils
提供集合操作的便捷方法,如判断空、合并、转换集合等。
-
功能:
static boolean isEmpty(Collection<?> coll)
: 检查集合是否为空。static <T> List<T> subtract(List<T> a, List<T> b)
: 返回两个列表的差集。static <T> boolean containsAll(Collection<T> a, Collection<T> b)
: 检查集合a是否包含集合b中的所有元素。static <T> int frequency(Collection<T> collection, T object)
: 计算集合中某个对象出现的次数。static <T> List<T> union(List<T> a, List<T> b)
: 返回两个列表的并集。
-
示例:
// 检查集合是否为空 boolean empty = CollectionUtils.isEmpty(Arrays.asList()); // 返回两个列表的差集 List<Integer> a = Arrays.asList(1, 2, 3); List<Integer> b = Arrays.asList(2, 3, 4); List<Integer> diff = CollectionUtils.subtract(a, b); // 检查集合a是否包含集合b中的所有元素 boolean containsAll = CollectionUtils.containsAll(a, b); // 计算集合中某个对象出现的次数 int count = CollectionUtils.frequency(a, 2); // 返回两个列表的并集 List<Integer> union = CollectionUtils.union(a, b);
MapUtils
提供Map操作的便捷方法,如判断空、获取值等。
-
功能:
static boolean isEmpty(Map<?, ?> map)
: 检查映射是否为空。static <K, V> Map<K, V> invertMap(Map<V, K> map)
: 反转映射的键值对。static <K, V> V get(Map<K, V> map, K key, V defaultValue)
: 获取映射中的值,如果不存在则返回默认值。static <K, V> Map<K, V> putAll(Map<K, V> map, Map<? extends K, ? extends V> other)
: 将另一个映射的所有条目添加到当前映射中。static <K, V> boolean isEqualMap(Map<K, V> map1, Map<K, V> map2)
: 比较两个映射是否相等。
-
示例:
// 检查映射是否为空 boolean empty = MapUtils.isEmpty(new HashMap<>()); // 反转映射的键值对 Map<String, Integer> map = new HashMap<>(); map.put("one", 1); map.put("two", 2); Map<Integer, String> inverted = MapUtils.invertMap(map); // 获取映射中的值,如果不存在则返回默认值 Integer value = MapUtils.get(map, "three", 0); // 将另一个映射的所有条目添加到当前映射中 Map<String, Integer> other = new HashMap<>(); other.put("three", 3); MapUtils.putAll(map, other); // 比较两个映射是否相等 boolean equal = MapUtils.isEqualMap(map, other);
ArrayUtils
提供数组操作的便捷方法,如判断空、合并、转换数组等。
-
功能:
static boolean isEmpty(Object[] array)
: 检查数组是否为空。static int[] add(int[] array, int element)
: 向数组中添加一个元素。static int indexOf(int[] array, int value)
: 查找数组中某个值的索引。static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive)
: 获取数组的子数组。static int[] removeElement(int[] array, int element)
: 从数组中移除指定元素。
-
示例:
// 检查数组是否为空 boolean empty = ArrayUtils.isEmpty(new int[] {}); // 向数组中添加一个元素 int[] array = {1, 2, 3}; int[] newArray = ArrayUtils.add(array, 4); // 查找数组中某个值的索引 int index = ArrayUtils.indexOf(array, 2); // 获取数组的子数组 int[] subArray = ArrayUtils.subarray(array, 1, 3); // 从数组中移除指定元素 int[] removedArray = ArrayUtils.removeElement(array, 2);
Lists
提供列表操作的便捷方法,如创建不可变列表、转换列表等。
-
功能:
static <T> List<T> newArrayList()
: 创建一个新的空列表。static <T> List<T> newArrayList(T... elements)
: 创建一个新的列表并初始化元素。static <T> List<T> newLinkedList()
: 创建一个新的空链表。static <T> List<T> newArrayListWithCapacity(int initialCapacity)
: 创建一个新的空列表并指定初始容量。static <T> List<T> newLinkedListWithCapacity(int initialCapacity)
: 创建一个新的空链表并指定初始容量。
-
示例:
// 创建一个新的空列表 List<String> list = Lists.newArrayList(); // 创建一个新的列表并初始化元素 List<String> listWithElements = Lists.newArrayList("one", "two", "three"); // 创建一个新的空链表 List<String> linkedList = Lists.newLinkedList(); // 创建一个新的空列表并指定初始容量 List<String> listWithCapacity = Lists.newArrayListWithCapacity(10); // 创建一个新的空链表并指定初始容量 List<String> linkedListWithCapacity = Lists.newLinkedListWithCapacity(10);
Maps
提供Map操作的便捷方法,如创建不可变Map、转换Map等。
-
功能:
static <K, V> Map<K, V> newHashMap()
: 创建一个新的空哈希映射。static <K, V> Map<K, V> newLinkedHashMap()
: 创建一个新的空链式哈希映射。static <K, V> Map<K, V> newTreeMap()
: 创建一个新的空树映射。static <K, V> Map<K, V> newHashMapWithExpectedSize(int expectedSize)
: 创建一个新的空哈希映射并指定预期大小。static <K, V> Map<K, V> newLinkedHashMapWithExpectedSize(int expectedSize)
: 创建一个新的空链式哈希映射并指定预期大小。
-
示例:
// 创建一个新的空哈希映射 Map<String, Integer> hashMap = Maps.newHashMap(); // 创建一个新的空链式哈希映射 Map<String, Integer> linkedHashMap = Maps.newLinkedHashMap(); // 创建一个新的空树映射 Map<String, Integer> treeMap = Maps.newTreeMap(); // 创建一个新的空哈希映射并指定预期大小 Map<String, Integer> hashMapWithSize = Maps.newHashMapWithExpectedSize(10); // 创建一个新的空链式哈希映射并指定预期大小 Map<String, Integer> linkedHashMapWithSize = Maps.newLinkedHashMapWithExpectedSize(10);
字符串相关
StringUtils
提供字符串操作的便捷方法,如判断空、截取、替换字符串等。
-
功能:
static boolean isEmpty(String str)
: 检查字符串是否为空或仅包含空白字符。static String join(Iterable<?> iterable, char separator)
: 将可迭代对象连接成一个字符串,使用指定的分隔符。static String substringBefore(String str, String separator)
: 返回字符串中第一个出现的分隔符之前的部分。static String trimToEmpty(String str)
: 去除字符串两端的空白字符,如果字符串为空则返回空字符串。static String capitalize(String str)
: 将字符串的第一个字符大写。
-
示例:
// 检查字符串是否为空或仅包含空白字符 boolean empty = StringUtils.isEmpty(" "); // 将可迭代对象连接成一个字符串,使用指定的分隔符 String joined = StringUtils.join(Arrays.asList("one", "two", "three"), ','); // 返回字符串中第一个出现的分隔符之前的部分 String before = StringUtils.substringBefore("one,two,three", ","); // 去除字符串两端的空白字符,如果字符串为空则返回空字符串 String trimmed = StringUtils.trimToEmpty(" hello "); // 将字符串的第一个字符大写 String capitalized = StringUtils.capitalize("hello");
Splitter/Joiner
提供字符串分割和连接的便捷方法。
-
功能:
Splitter.on(char delimiter)
: 创建一个以指定字符为分隔符的拆分器。Splitter.fixedLength(int length)
: 创建一个固定长度的拆分器。Joiner.on(char delimiter)
: 创建一个以指定字符为分隔符的连接器。Splitter.trimResults()
: 去除拆分后的每个部分的空白字符。Joiner.skipNulls()
: 跳过连接时的null值。
-
示例:
// 创建一个以逗号为分隔符的拆分器 Iterable<String> parts = Splitter.on(',').split("one,two,three"); // 创建一个固定长度的拆分器 Iterable<String> fixedParts = Splitter.fixedLength(3).split("onetwothree"); // 创建一个以逗号为分隔符的连接器 String joined = Joiner.on(',').join(Arrays.asList("one", "two", "three")); // 去除拆分后的每个部分的空白字符 Iterable<String> trimmedParts = Splitter.on(',').trimResults().split(" one , two , three "); // 跳过连接时的null值 String joinedWithoutNulls = Joiner.on(',').skipNulls().join(Arrays.asList("one", null, "three"));
日期相关
DateUtils
提供日期操作的便捷方法,如解析、格式化日期等。
-
功能:
static Date addDays(Date date, int amount)
: 在给定日期上增加或减少指定天数。static Date truncate(Date date, int field)
: 截断日期到指定的时间单位。static Date parseDate(String str, String... parsePatterns)
: 使用多个解析模式解析日期字符串。static Date round(Date date, int field)
: 四舍五入日期到指定的时间单位。static long difference(Date date1, Date date2, int timeUnit)
: 计算两个日期之间的差异,以指定的时间单位表示。
-
示例:
// 在给定日期上增加5天 Date newDate = DateUtils.addDays(new Date(), 5); // 截断日期到月份 Date truncated = DateUtils.truncate(new Date(), Calendar.MONTH); // 使用多个解析模式解析日期字符串 Date parsedDate = DateUtils.parseDate("2023-10-01", "yyyy-MM-dd", "dd/MM/yyyy"); // 四舍五入日期到月份 Date rounded = DateUtils.round(new Date(), Calendar.MONTH); // 计算两个日期之间的差异,以天为单位 long difference = DateUtils.difference(new Date(), DateUtils.addDays(new Date(), 5), Calendar.DAY_OF_MONTH);
DateFormatUtils
提供日期格式化的便捷方法。
-
功能:
static String format(Date date, String pattern)
: 格式化日期为字符串。static String ISO_DATE_FORMAT
: ISO 8601日期格式。static String ISO_DATETIME_FORMAT
: ISO 8601日期时间格式。static String SHORT_DATE_FORMAT
: 短日期格式(如:yy-MM-dd
)。static String MEDIUM_DATE_FORMAT
: 中等日期格式(如:yyyy-MMM-dd
)。
-
示例:
// 格式化日期为字符串 String formatted = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"); // 使用ISO 8601日期格式 String isoDate = DateFormatUtils.ISO_DATE_FORMAT; // 使用ISO 8601日期时间格式 String isoDateTime = DateFormatUtils.ISO_DATETIME_FORMAT; // 使用短日期格式 String shortDate = DateFormatUtils.SHORT_DATE_FORMAT; // 使用中等日期格式 String mediumDate = DateFormatUtils.MEDIUM_DATE_FORMAT;
LocalDate
提供日期操作的便捷方法,基于Java 8的LocalDate类。
-
功能:
static LocalDate now()
: 获取当前日期。static LocalDate of(int year, int month, int dayOfMonth)
: 创建指定日期的LocalDate对象。static LocalDate plusDays(long days)
: 在当前日期上增加指定天数。static LocalDate minusDays(long days)
: 在当前日期上减少指定天数。static LocalDate withDayOfMonth(int dayOfMonth)
: 设置日期的天数部分。
-
示例:
// 获取当前日期 LocalDate today = LocalDate.now(); // 创建指定日期的LocalDate对象 LocalDate specificDate = LocalDate.of(2023, 10, 1); // 在当前日期上增加5天 LocalDate futureDate = today.plusDays(5); // 在当前日期上减少5天 LocalDate pastDate = today.minusDays(5); // 设置日期的天数部分 LocalDate newDate = today.withDayOfMonth(15);
计时
StopWatch
提供计时操作的便捷方法,用于测量代码执行时间。
-
功能:
void start()
: 开始计时。void stop()
: 停止计时。long getTotalTimeMillis()
: 获取总时间(毫秒)。String prettyPrint()
: 以可读格式打印计时结果。void reset()
: 重置计时器。
-
示例:
// 创建并开始计时 StopWatch stopWatch = new StopWatch(); stopWatch.start(); // 执行一些操作 Thread.sleep(1000); // 停止计时 stopWatch.stop(); // 获取总时间(毫秒) long totalTime = stopWatch.getTotalTimeMillis(); // 以可读格式打印计时结果 System.out.println(stopWatch.prettyPrint()); // 重置计时器 stopWatch.reset();
相关依赖
IO相关
- FileUtils 和 IOUtils
-
依赖:
commons-io:commons-io
-
Maven坐标:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency>
-
集合/数组相关
-
CollectionUtils 和 MapUtils
-
依赖:
org.apache.commons:commons-collections4
-
Maven坐标:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.4</version> </dependency>
-
-
ArrayUtils
-
依赖:
org.apache.commons:commons-lang3
-
Maven坐标:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
-
-
Lists 和 Maps
-
依赖:
com.google.guava:guava
-
Maven坐标:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>31.0.1-jre</version> </dependency>
-
字符串相关
-
StringUtils
-
依赖:
org.apache.commons:commons-lang3
-
Maven坐标:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
-
-
Splitter 和 Joiner
-
依赖:
com.google.guava:guava
-
Maven坐标:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>31.0.1-jre</version> </dependency>
-
日期相关
-
DateUtils 和 DateFormatUtils
-
依赖:
org.apache.commons:commons-lang3
-
Maven坐标:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
-
-
LocalDate
- 依赖:
- Java 8及以上版本自带,无需额外依赖。
- 依赖:
计时
- StopWatch
-
依赖:
org.springframework:spring-core
-
Maven坐标:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.10</version> </dependency>
-
完整的 pom.xml
示例
<dependencies>
<!-- Spring Boot Starter Web (可选,根据项目需求) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- Apache Commons Collections -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<!-- Apache Commons Lang -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- Google Guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
<!-- Spring Core for StopWatch -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.10</version>
</dependency>
</dependencies>
注意事项
-
Spring Boot版本管理:如果你使用的是Spring Boot项目,建议使用Spring Boot的依赖管理来管理这些依赖的版本。你可以在
pom.xml
中添加spring-boot-dependencies
作为父项目,这样可以简化依赖版本的管理。 -
版本兼容性:确保你使用的依赖版本与你的Spring Boot版本兼容。Spring Boot通常会推荐一些特定版本的依赖,以确保最佳的兼容性和稳定性。