作为一名 Java 开发工程师,你每天都在与各种 Java 标准库打交道。熟练掌握 Java 中的常用 API 是提高代码质量、提升开发效率的关键技能之一。
本文将带你全面了解 Java 开发中最常用的 API 类和接口,包括:
java.lang
包中的核心类(如String
,Object
,Math
,System
)- 集合框架(
Collection
,List
,Set
,Map
) - 多线程相关类(
Thread
,Runnable
,ExecutorService
) - IO/NIO 流操作(
File
,InputStream
,BufferedReader
,Files
) - 时间日期 API(
LocalDate
,LocalTime
,ZonedDateTime
,DateTimeFormatter
) - 异常处理(
Exception
,try-with-resources
) - 工具类(
Arrays
,Collections
,Objects
)
并通过丰富的代码示例和真实业务场景讲解,帮助你写出更健壮、更简洁、更具可维护性的 Java 代码。
🧱 一、Java 核心包:java.lang
java.lang
是 Java 最基础的包,JVM 启动时自动加载,无需手动导入。
1. Object
------ 所有类的父类
typescript
public class Person {
@Override
public String toString() {
return "Person{}";
}
}
✅ 所有类默认继承
Object
,常用方法:toString()
、equals()
、hashCode()
、getClass()
2. String
------ 不可变字符串
ini
String s = "Hello";
s += " World"; // 实际创建了一个新对象
✅ 字符串拼接建议使用
StringBuilder
或String.format
ini
String result = String.format("Name: %s, Age: %d", name, age);
3. Math
------ 数学运算工具类
ini
int max = Math.max(10, 20);
double sqrt = Math.sqrt(16);
int random = (int) (Math.random() * 100);
4. System
------ 系统级操作
ini
long startTime = System.currentTimeMillis();
// do something
long duration = System.currentTimeMillis() - startTime;
✅
System.out.println()
、System.exit(0)
、System.getProperty()
等也非常常用
📚 二、集合框架:java.util
集合框架是 Java 编程中最常使用的部分之一,主要包括以下几大接口和实现类:
接口 | 实现类 | 特点 |
---|---|---|
List |
ArrayList , LinkedList |
有序、可重复 |
Set |
HashSet , TreeSet |
无序、不可重复 |
Map |
HashMap , TreeMap , LinkedHashMap |
键值对结构 |
示例:
ini
List<String> names = new ArrayList<>();
names.add("Tom");
names.add("Jerry");
Set<Integer> uniqueNumbers = new HashSet<>();
uniqueNumbers.add(1);
uniqueNumbers.add(2);
Map<String, Integer> scores = new HashMap<>();
scores.put("Tom", 90);
scores.put("Jerry", 85);
Java 8+ 新特性支持:
rust
// 使用 Stream API 进行过滤
List<String> filtered = names.stream()
.filter(name -> name.startsWith("T"))
.toList();
// 遍历 Map
scores.forEach((name, score) -> System.out.println(name + ": " + score));
⏱ 三、时间日期 API:java.time
在 Java 8 之前,我们通常使用 Date
和 SimpleDateFormat
,但它们存在线程安全问题。Java 8 引入了全新的 java.time
包,推荐使用。
常用类:
类名 | 说明 |
---|---|
LocalDate |
本地日期(年月日) |
LocalTime |
本地时间(时分秒) |
LocalDateTime |
本地日期时间 |
ZonedDateTime |
带时区的日期时间 |
Duration / Period |
表示时间间隔 |
DateTimeFormatter |
格式化/解析日期 |
示例:
ini
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime current = LocalDateTime.now();
// 格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = current.format(formatter);
// 解析
LocalDateTime parsed = LocalDateTime.parse("2025-07-14 14:30:00", formatter);
📁 四、IO/NIO 操作:java.io
与 java.nio
Java 提供了两种文件读写方式:传统的 java.io
和现代的 java.nio
。
1. File
类
ini
File file = new File("data.txt");
if (!file.exists()) {
file.createNewFile();
}
2. BufferedReader
------ 逐行读取文本文件
arduino
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
3. Files
工具类(NIO)
ini
Path path = Paths.get("data.txt");
List<String> lines = Files.readAllLines(path); // 一次性读取所有行
Files.write(path, "Hello World\n".getBytes(), StandardOpenOption.APPEND);
🧵 五、多线程编程:java.util.concurrent
Java 支持并发编程,常见类包括:
类名 | 说明 |
---|---|
Thread |
线程类 |
Runnable |
可执行任务接口 |
Callable |
有返回值的任务接口 |
ExecutorService |
线程池管理器 |
Future |
异步计算结果 |
CompletableFuture |
异步任务编排(Java 8+) |
示例:
ini
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> {
System.out.println("Task executed in thread: " + Thread.currentThread().getName());
});
executor.shutdown(); // 关闭线程池
🔄 六、异常处理:Throwable
体系
Java 的异常体系分为两大类:
类型 | 是否必须处理 | 说明 |
---|---|---|
Error |
否 | 虚拟机错误,如 OutOfMemoryError |
Exception |
是 | 可控异常,如 IOException、NullPointerException |
try-with-resources(Java 7+)
csharp
try (FileInputStream fis = new FileInputStream("file.txt")) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
🔧 七、实用工具类
1. Arrays
------ 数组操作
ini
int[] arr = {3, 1, 4, 1, 5};
Arrays.sort(arr); // 排序
boolean found = Arrays.binarySearch(arr, 4) >= 0; // 二分查找
2. Collections
------ 集合工具类
ini
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
Collections.reverse(list); // 反转
Collections.shuffle(list); // 打乱顺序
3. Objects
------ 对象工具类
csharp
String str = null;
System.out.println(Objects.toString(str, "default")); // 输出 default
System.out.println(Objects.equals(null, str)); // 安全比较
💡 八、实际应用场景与案例解析
场景1:读取配置文件并构建 Map
ini
Map<String, String> config = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader("config.properties"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("=");
if (parts.length == 2) {
config.put(parts[0], parts[1]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
场景2:定时任务调度
ini
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
System.out.println("执行定时任务:" + LocalDateTime.now());
}, 0, 1, TimeUnit.SECONDS);
场景3:异步处理用户注册逻辑
c
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// 发送邮件或短信
sendWelcomeEmail("user@example.com");
});
future.exceptionally(ex -> {
log.error("发送失败", ex);
return null;
});
🚫 九、常见错误与注意事项
错误 | 正确做法 |
---|---|
使用 == 判断字符串内容是否相等 |
应使用 .equals() |
在多线程环境下使用 SimpleDateFormat |
应使用 DateTimeFormatter |
修改正在遍历的集合 | 使用迭代器或复制后再修改 |
忽略关闭资源(如流、连接) | 使用 try-with-resources |
忽略空指针异常 | 使用 Optional 或 Objects 工具类 |
使用 Thread.sleep() 替代定时任务 |
应使用 ScheduledExecutorService |
在 Lambda 中修改外部变量 | 外部变量应为 final 或等效不变量 |
📊 十、总结:Java 常用 API 一览表
类/接口 | 所属包 | 主要用途 |
---|---|---|
Object |
java.lang | 所有类的基类 |
String |
java.lang | 字符串处理 |
Math |
java.lang | 数学运算 |
System |
java.lang | 系统操作 |
List/Set/Map |
java.util | 集合操作 |
Stream |
java.util.stream | 函数式集合操作 |
LocalDate/Time |
java.time | 时间日期处理 |
File/BufferedReader |
java.io | 文件读写 |
Files |
java.nio.file | NIO 文件操作 |
Thread/Runnable |
java.lang | 多线程 |
ExecutorService |
java.util.concurrent | 线程池 |
CompletableFuture |
java.util.concurrent | 异步编程 |
Exception |
java.lang | 异常处理 |
Arrays/Collections |
java.util | 集合工具 |
Objects |
java.util | 对象工具 |
📎 十一、附录:API 使用技巧速查表
功能 | 示例 |
---|---|
字符串格式化 | String.format("Name: %s", name) |
集合排序 | Collections.sort(list) |
获取当前时间 | LocalDateTime.now() |
读取文件全部内容 | Files.readAllLines(path) |
写入文件 | Files.write(path, content.getBytes()) |
创建线程池 | Executors.newFixedThreadPool(n) |
异步任务 | CompletableFuture.supplyAsync(() -> ...) |
安全比较对象 | Objects.equals(a, b) |
判空处理 | Optional.ofNullable(obj).ifPresent(...) |
遍历 Map | map.forEach((k, v) -> ...) |
如果你正在准备一篇面向初学者的技术博客,或者希望系统回顾 Java 基础知识,这篇文章将为你提供完整的知识体系和实用的编程技巧。
欢迎点赞、收藏、转发,也欢迎留言交流你在实际项目中遇到的 API 相关问题。我们下期再见 👋
📌 关注我,获取更多Java核心技术深度解析!