Java常用API详解与代码实践
一、字符串处理类
1. String类
// 字符串基础操作
String str = "Hello,Java!";
System.out.println(str.substring(7)); // 输出"Java!"
System.out.println(str.indexOf("Java")); // 输出7
// 正则表达式匹配
String email = "test@example.com";
System.out.println(email.matches("^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$")); // true
2. StringBuilder/StringBuffer
// 字符串拼接性能优化
StringBuilder sb = new StringBuilder();
sb.append("Java")
.append(17)
.insert(0, "Version: ");
System.out.println(sb.toString()); // 输出"Version: Java17"
二、集合框架
1. List接口
// ArrayList示例
List<String> list = new ArrayList<>();
list.add("Apple");
list.add(0, "Banana");
System.out.println(list.get(1)); // 输出"Apple"
// LinkedList特殊操作
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.addFirst(10);
linkedList.pollLast();
2. Map接口
// HashMap使用
Map<String, Integer> map = new HashMap<>();
map.put("Java", 1995);
map.computeIfAbsent("Python", k -> 1991);
// TreeMap排序
TreeMap<Integer, String> treeMap = new TreeMap<>(Comparator.reverseOrder());
treeMap.put(3, "Three");
treeMap.put(1, "One");
System.out.println(treeMap.firstKey()); // 输出3
三、IO流体系
1. 文件操作
// 使用NIO读取文件
Path path = Paths.get("test.txt");
try (Stream<String> lines = Files.lines(path)) {
lines.filter(line -> line.contains("Java"))
.forEach(System.out::println);
}
// 缓冲流复制文件
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line.toUpperCase());
writer.newLine();
}
}
四、日期时间API(Java 8+)
1. 基础日期操作
LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plusWeeks(1);
System.out.println(today.isBefore(nextWeek)); // true
// 日期格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println(today.format(formatter));
2. 时间差计算
LocalDateTime start = LocalDateTime.of(2023, 1, 1, 9, 0);
LocalDateTime end = LocalDateTime.now();
Duration duration = Duration.between(start, end);
System.out.println(duration.toDays() + " days");
五、多线程编程
1. 线程基础
// 实现Runnable接口
new Thread(() -> {
IntStream.range(1, 5).forEach(i -> {
System.out.println("Task-" + i);
try { Thread.sleep(500); }
catch (InterruptedException e) {}
});
}).start();
2. 线程池管理
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> System.out.println("Task1"));
executor.submit(() -> System.out.println("Task2"));
executor.shutdown();
六、异常处理机制
1. 自定义异常
class BalanceException extends Exception {
public BalanceException(String message) {
super(message);
}
}
void withdraw(double amount) throws BalanceException {
if (amount > balance) {
throw new BalanceException("余额不足");
}
// 扣款逻辑
}
七、反射机制
1. 动态调用方法
Class<?> clazz = Class.forName("com.example.User");
Object user = clazz.getDeclaredConstructor().newInstance();
Method setName = clazz.getMethod("setName", String.class);
setName.invoke(user, "张三");
Field ageField = clazz.getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(user, 25);
最佳实践建议
- 集合初始化时指定容量(如
new ArrayList<>(100)
) - 使用
Objects.equals()
进行空安全比较 - IO操作始终使用try-with-resources
- 多线程环境使用并发集合(如ConcurrentHashMap)
- 时间处理优先使用Java 8+ API
通过掌握这些核心API的用法,结合具体业务场景灵活运用,可以显著提升Java开发效率与代码质量。建议通过官方文档深入了解各个类的完整方法体系。