在Java开发过程中,开发者经常会遇到一些重复性高、但又非常基础的代码段。掌握这些“常用代码”不仅能提高开发效率,还能帮助新手更快地理解Java语言的核心机制。以下是一些在日常开发中经常用到的Java代码示例,涵盖基本语法、集合操作、异常处理、文件读写等多个方面。
一、字符串处理
```java
// 判断字符串是否为空
if (str == null || str.trim().isEmpty()) {
System.out.println("字符串为空");
}
// 字符串转整数(带异常处理)
try {
int num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("转换失败:" + e.getMessage());
}
```
二、集合操作
```java
// 创建并遍历List
List
list.add("Java");
list.add("Python");
for (String item : list) {
System.out.println(item);
}
// 使用Lambda表达式遍历Map
Map
map.put("A", 1);
map.put("B", 2);
map.forEach((key, value) -> System.out.println(key + " : " + value));
```
三、文件读写
```java
// 读取文件内容
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// 写入文件
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("Hello, Java!");
} catch (IOException e) {
e.printStackTrace();
}
```
四、异常处理
```java
// 自定义异常类
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
// 抛出并捕获自定义异常
try {
throw new MyException("这是一个自定义异常");
} catch (MyException e) {
System.out.println("捕获到异常:" + e.getMessage());
}
```
五、日期与时间处理
```java
// 获取当前日期和时间
LocalDateTime now = LocalDateTime.now();
System.out.println("当前时间:" + now);
// 格式化日期
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(formatter);
System.out.println("格式化后的时间:" + formattedDate);
```
六、多线程与并发
```java
// 使用Thread类创建线程
class MyThread extends Thread {
public void run() {
System.out.println("线程运行中...");
}
}
MyThread thread = new MyThread();
thread.start();
// 使用Runnable接口实现多线程
Runnable task = () -> System.out.println("任务执行中...");
Thread t = new Thread(task);
t.start();
```
七、常用工具类方法
```java
// 检查对象是否为null
public static boolean isNull(Object obj) {
return obj == null;
}
// 判断两个字符串是否相等(忽略大小写)
public static boolean equalsIgnoreCase(String a, String b) {
return a != null && b != null && a.equalsIgnoreCase(b);
}
```
总结
以上是一些Java开发中常见的代码片段,虽然看似简单,但在实际项目中却非常重要。熟练掌握这些内容,不仅可以提升编码效率,还能增强代码的可读性和健壮性。建议开发者在日常工作中不断积累和总结,形成自己的“代码库”,以便在需要时快速调用。