JAVA 常用工具类详解
小标题:JAVA 常用工具类大揭秘:代码世界的多面手
一、引言
在 Java 的代码宇宙里,有像Date、Math、Random等一系列工具类,默默支撑起程序的多样功能。它们极大地简化了开发流程,无论是日常的业务逻辑处理、复杂的算法设计,还是网络通信、多线程并发,都离不开这些工具类的身影,让我们得以高效地构建出功能强大的应用程序。
二、日期时间相关工具类
(一)Date 类
Date 类作为 Java 早期用于处理日期和时间的核心类,承载着基本的时间表示功能。它记录的是自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数。以下是简单的示例:
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateExample {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(now);
System.out.println("当前时间:" + formattedDate);
}
}
这段代码创建了一个 Date 对象获取当前时间,并借助 SimpleDateFormat 将其格式化为常见的字符串格式输出。
(二)LocalDateTime 类
与 Date 类相比,LocalDateTime 提供了更丰富且易用的日期时间操作方法,它属于 Java 8 引入的新日期时间 API。例如:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println("当前本地时间:" + formattedDateTime);
LocalDateTime futureTime = now.plusHours(2).plusMinutes(30);
System.out.println("两小时三十分后的时间:" + futureTime.format(formatter));
}
}
这里不仅能便捷获取当前时间,还能轻松进行时间的加减运算,展现出其强大的功能性。
(三)Calendar 类
Calendar 类为日期时间的处理提供了高度灵活的方式,它可以精准地设置和获取年、月、日、时、分、秒等各个字段。示例如下:
import java.util.Calendar;
public class CalendarExample {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("今天是:" + year + "-" + month + "-" + day);
calendar.add(Calendar.DAY_OF_MONTH, 7);
int nextWeekDay = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("一周后的日期:" + year + "-" + month + "-" + nextWeekDay);
}
}
通过 get 方法获取当前日期各部分信息,利用 add 方法进行日期推算。
三、数学运算工具类:Math
Java 的 Math 类仿佛一个装满数学魔法的工具箱,涵盖了大量实用的数学运算方法。
public class MathExample {
public static void main(String[] args) {
int absValue = Math.abs(-5);
System.out.println("绝对值:" + absValue);
double maxValue = Math.max(3.5, 7.2);
System.out.println("最大值:" + maxValue);
double powerResult = Math.pow(2, 3);
System.out.println("2 的 3 次方:" + powerResult);
double sqrtValue = Math.sqrt(16);
System.out.println("16 的平方根:" + sqrtValue);
}
}
从求绝对值、最大值,到幂运算、平方根,只需简单调用相应方法,就能快速得到结果。
四、随机数生成工具类:Random
当程序需要引入一些不确定性时,Random 类就派上用场了。
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
int randomInt = random.nextInt(100);
System.out.println("生成 0 - 99 之间的随机整数:" + randomInt);
double randomDouble = random.nextDouble();
System.out.println("生成 0 - 1 之间的随机小数:" + randomDouble);
int rangeRandom = random.nextInt(50) + 50;
System.out.println("生成 50 - 99 之间的随机整数:" + rangeRandom);
}
}
无论是限定范围的整数随机数,还是 0 到 1 之间的小数随机数,Random 类都能轻松生成。
五、线程相关工具类:Thread
在多任务并行的场景下,Thread 类是开启线程的关键。
public class ThreadExample extends Thread {
@Override
public void run() {
System.out.println("线程正在运行:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadExample thread1 = new ThreadExample();
thread1.start();
Thread thread2 = new Thread(() -> {
System.out.println("匿名线程运行:" + Thread.currentThread().getName());
});
thread2.start();
}
}
这里展示了继承 Thread 类并重写 run 方法创建线程,以及使用匿名内部类结合 Thread 构造函数创建线程的两种常见方式,随后通过 start 方法启动线程,让它们并发执行。
六、异常处理工具类:Throwable
异常如同程序运行中的暗礁,Throwable 类及其子类构成的异常处理体系则是保驾护航的灯塔。
public class ThrowableExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("捕获到算术异常:" + e.getMessage());
} finally {
System.out.println("无论是否异常,此代码块都会执行");
}
}
}
利用 try-catch-finally 结构,程序能在遭遇异常时优雅应对,避免崩溃,同时确保关键资源的释放或后续处理得以完成。
七、对象实例工具类:Instance(这里以 Class.forName 为例)
在一些动态加载类、创建对象的场景中,反射机制提供了强大的功能。
public class InstanceExample {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class<?> clazz = Class.forName("java.util.Date");
Object instance = clazz.newInstance();
System.out.println("通过反射创建的对象:" + instance);
}
}
通过指定类的全限定名,利用 Class.forName 获取 Class 对象,进而创建实例,这种方式在框架开发等需要灵活加载类的场景中极为有用。
八、时间间隔工具类:Period 和 Duration
(一)Period 类 用于处理日期之间的间隔,聚焦于年、月、日维度。
import java.time.LocalDate;
import java.time.Period;
public class PeriodExample {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2023, 3, 15);
Period period = Period.between(startDate, endDate);
System.out.println("相差年:" + period.getYears());
System.out.println("相差月:" + period.getMonths());
System.out.println("相差日:" + period.getDays());
}
}
精准算出两个日期在年、月、日层面的差值。
(二)Duration 类
侧重于时间点之间的间隔,精确到秒、纳秒级别。
import java.time.Duration;
import java.time.LocalDateTime;
public class DurationExample {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2023, 1, 1, 10, 0, 0);
LocalDateTime end = LocalDateTime.of(2023, 1, 1, 12, 30, 0);
Duration duration = Duration.between(start, end);
System.out.println("相差小时:" + duration.toHours());
System.out.println("相差分钟:" + duration.toMinutes());
System.out.println("相差秒:" + duration.getSeconds());
}
}
清晰呈现两个时间点的小时、分钟、秒间隔。
九、高精度数值运算工具类:BigDecimal
在涉及货币等对精度要求极高的数值计算场景,BigDecimal 是不二之选。
import java.math.BigDecimal;
public class BigDecimalExample {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("10.5");
BigDecimal num2 = new BigDecimal("2.5");
BigDecimal sum = num1.add(num2);
BigDecimal difference = num1.subtract(num2);
BigDecimal product = num1.multiply(num2);
BigDecimal quotient = num1.divide(num2);
System.out.println("加法结果:" + sum);
System.out.println("减法结果:" + difference);
System.out.println("乘法结果:" + product);
System.out.println("除法结果:" + quotient);
}
}
通过其封装的方法进行精确四则运算,避免浮点数运算的精度损失。
十、集合操作工具类:Collections
Collections 类为 Java 集合框架提供了一系列便捷的静态方法,让集合操作事半功倍。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
Collections.sort(numbers);
System.out.println("排序后的集合:" + numbers);
int index = Collections.binarySearch(numbers, 8);
System.out.println("元素 8 的索引:" + index);
Collections.shuffle(numbers);
System.out.println("打乱后的集合:" + numbers);
}
}
从排序、二分查找,到随机打乱,涵盖了日常开发中频繁使用的集合操作。
十一、属性文件操作工具类:Properties
在配置信息管理方面,Properties 类发挥着重要作用。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesExample {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
// 加载属性文件
properties.load(new FileInputStream("config.properties"));
String username = properties.getProperty("username");
System.out.println("用户名:" + username);
// 修改属性值
properties.setProperty("password", "newpassword");
// 保存属性文件
properties.store(new FileOutputStream("config.properties"), "Updated config");
}
}
轻松实现属性文件的加载、读取、修改与保存,方便程序的配置管理。
十二、流处理工具类:Stream
Java 8 引入的 Stream API 革新了集合数据的处理方式,让代码更加简洁高效。
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("偶数集合:" + evenNumbers);
List<Integer> squaredNumbers = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println("平方数集合:" + squaredNumbers);
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println("总和:" + sum);
}
}
通过链式调用 filter、map、reduce 等操作,在一行行简洁的代码中完成复杂的数据筛选、转换与聚合。
十三、网络编程相关工具类
(一)URL 类和 URLConnection 类
当需要与网络资源交互时,它们是得力助手。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class URLExample {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine())!= null) {
System.out.println(line);
}
reader.close();
}
}
这段代码创建 URL 对象,建立连接后读取网页内容并输出,实现了简单的网络资源访问。
(二)InetAddress 类
用于获取网络主机的相关信息,如 IP 地址。
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressExample {
public static void main(String[] args) throws UnknownHostException {
InetAddress localAddress = InetAddress.getLocalHost();
System.out.println("本地主机 IP:" + localAddress.getHostAddress());
InetAddress[] addresses = InetAddress.getAllByName("www.example.com");
for (InetAddress address : addresses) {
System.out.println("域名对应的 IP:" + address.getHostAddress());
}
}
}
方便快捷地查询本地或远程主机的 IP 信息。
(三)Socket 类
基于 TCP 协议实现网络通信的基石。
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketExample {
public static void main(String[] args) throws IOException {
// 服务器端
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器启动,等待连接...");
Socket clientSocket = serverSocket.accept();
InputStream inputStream = clientSocket.getInputStream();
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
String message = new String(buffer, 0, length);
System.out.println("收到客户端消息:" + message);
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write("消息已收到".getBytes());
clientSocket.close();
serverSocket.close();
// 客户端
Socket socket = new Socket("localhost", 8888);
OutputStream clientOutputStream = socket.getOutputStream();
clientOutputStream.write("你好,服务器".getBytes());
InputStream clientInputStream = socket.getInputStream();
byte[] clientBuffer = new byte[1024];
int clientLength = clientInputStream.read(clientBuffer);
String clientMessage = new String(clientBuffer, 0, clientLength);
System.out.println("收到服务器回复:" + clientMessage);
socket.close();
}
}
展示了服务器与客户端通过 Socket 建立连接、收发消息的完整流程,构建起基本的网络通信架构。
十四、总结
这些形形色色的工具类,每一个都在特定领域独当一面,共同编织起 Java 编程的坚固基石。熟练掌握它们,犹如手握利刃,无论是应对日常业务开发中的琐碎需求,还是攻坚复杂系统的关键难题,都能游刃有余,大幅提升编程的效率与质量,让我们在代码世界里披荆斩棘,创造出更多精彩的应用。
最近一直在研究AI公众号爆文的运维逻辑,也在学习各种前沿的AI技术,加入了不会笑青年和纯洁的微笑两位大佬组织起来的知识星球,也开通了自己的星球:
怡格网友圈,地址是:https://wx.zsxq.com/group/51111855584224
这是一个付费的星球,暂时我还没想好里面放什么,现阶段不建议大家付费和进入我自己的星球,即使有不小心付费的,我也会直接退费,无功不受禄。如果你也对AI特别感兴趣,推荐你付费加入他们的星球:
AI俱乐部,地址是:https://t.zsxq.com/mRfPc 。
建议大家先加 微信号:yeegee2024 或者关注微信公众号:yeegeexb2014 咱们产品成型了之后,咱们再一起进入星球,一起探索更美好的未来!