3. 高级主题
3.1 异常处理
异常处理机制用于处理程序运行过程中可能出现的错误。Java 提供了 try-catch-finally
语句块来捕获和处理异常。
-
基本异常处理:
public class ExceptionDemo { public static void main(String[] args) { try { int result = 10 / 0; // 可能抛出异常的代码 } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); // 处理异常 } finally { System.out.println("This block always executes."); } } }
try
:放置可能会抛出异常的代码。catch
:捕获和处理异常。finally
:无论是否发生异常都会执行的代码块,通常用于释放资源(如关闭文件、网络连接)。
-
自定义异常:
public class CustomException extends Exception { public CustomException(String message) { super(message); } } public class CustomExceptionDemo { public static void main(String[] args) { try { throw new CustomException("This is a custom exception."); } catch (CustomException e) { System.out.println(e.getMessage()); } } }
3.2 文件操作
Java 提供了文件读写操作的类,包括 File
, FileInputStream
, FileOutputStream
, BufferedReader
, 和 BufferedWriter
。
-
读取文件:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReadDemo { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
-
写入文件:
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileWriteDemo { public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) { bw.write("Hello, world!"); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
3.3 集合框架
Java 集合框架提供了多种数据结构和算法的实现,如 List
, Set
, Map
。
-
List(有序集合):
import java.util.ArrayList; import java.util.List; public class ListDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); for (String fruit : list) { System.out.println(fruit); } } }
-
Set(无序集合):
import java.util.HashSet; import java.util.Set; public class SetDemo { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Cherry"); for (String fruit : set) { System.out.println(fruit); } } }
-
Map(键值对集合):
import java.util.HashMap; import java.util.Map; public class MapDemo { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("Apple", 1); map.put("Banana", 2); map.put("Cherry", 3); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
3.4 多线程与并发
Java 提供了多线程编程的支持,通过 Thread
类和 Runnable
接口实现。
-
创建和启动线程:
public class MyThread extends Thread { public void run() { System.out.println("Thread is running."); } public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // 启动线程 } }
-
使用
Runnable
接口:public class MyRunnable implements Runnable { public void run() { System.out.println("Runnable is running."); } public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); // 启动线程 } }
-
线程同步:
public class Counter { private int count = 0; public synchronized void increment() { count++; } public int getCount() { return count; } public static void main(String[] args) { Counter counter = new Counter(); Runnable task = () -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }; Thread t1 = new Thread(task); Thread t2 = new Thread(task); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Count: " + counter.getCount()); } }
3.5 Java I/O
Java I/O 包括字节流和字符流,用于读写不同类型的数据。
-
字节流:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ByteStreamDemo { public static void main(String[] args) { try (FileOutputStream fos = new FileOutputStream("data.bin")) { fos.write(65); // 写入字节 } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } try (FileInputStream fis = new FileInputStream("data.bin")) { int data = fis.read(); // 读取字节 System.out.println("Data: " + data); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
-
字符流:
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CharStreamDemo { public static void main(String[] args) { try (FileWriter fw = new FileWriter("text.txt")) { fw.write("Hello, world!"); // 写入字符 } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } try (FileReader fr = new FileReader("text.txt")) { int c; while ((c = fr.read()) != -1) { System.out.print((char) c); // 读取字符 } } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
3.6 网络编程
Java 提供了网络编程的支持,通过 Socket
和 ServerSocket
类实现客户端和服务器端的通信。
-
简单的服务器端:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(12345)) { System.out.println("Server is listening on port 12345"); Socket socket = serverSocket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = in.readLine(); System.out.println("Received: " + message); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
-
简单的客户端:
import java.io.PrintWriter; import java.net.Socket; public class Client { public static void main(String[] args) { try (Socket socket = new Socket("localhost", 12345)) { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Hello from the client!"); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
3.7 Java 8 及以后特性
Java 8 引入了许多新特性,包括 Lambda 表达式、Stream API 和新的日期时间 API。
-
Lambda 表达式:
interface MathOperation { int operate(int a, int b); } public class LambdaDemo { public static void main(String[] args) { MathOperation add = (a, b) -> a + b; System.out.println("Addition: " + add.operate(5, 3)); } }
-
Stream API:
import java.util.Arrays; import java.util.List; public class StreamDemo { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .filter(name -> name.startsWith("A")) .forEach(System.out::println); } }
-
新的日期时间 API:
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeDemo { public static void main(String[] args) { LocalDate today = LocalDate.now(); LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); String formattedDate = now.format(formatter); System.out.println("Today: " + today); System.out.println("Now: " + formattedDate); } }
3.8 JVM 与性能优化
Java 虚拟机(JVM)是 Java 程序运行的环境。了解 JVM 的工作原理有助于优化程序性能。
-
垃圾回收:JVM 自动管理内存,通过垃圾回收机制清理不再使用的对象。常用的垃圾回收器有串行垃圾回收器、并行垃圾回收器和 G1 垃圾回收器。
示例:
java -XX:+UseG1GC -jar your-application.jar
-
JVM 性能调优:
- 堆内存大小:可以通过
-Xms
和-Xmx
参数设置初始和最大堆内存。 - 线程栈大小:可以通过
-Xss
参数设置每个线程的栈大小。
示例:
java -Xms512m -Xmx2g -Xss1m -jar your-application.jar
- 堆内存大小:可以通过
通过以上内容,你可以深入理解 Java 编程的高级特性和技术。这些知识将帮助你编写高效、可维护和可靠的 Java 应用程序。