Java 的 I/O 體系、異常處理機制、物件序列化、資料庫連線以及網路程式設計,構成了 Java 後端開發的核心基石。本文將系統性地梳理這五大核心模組,透過實戰程式碼範例,幫助開發者建立完整的知識體系,提升工程實戰能力。
Java 的 java.io 套件提供了完整的 I/O 支援,所有流類別繼承自四大抽象基類:InputStream、OutputStream、Reader、Writer。流可理解為資料序列,輸入流從來源讀取資料,輸出流向目的地寫入資料。
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c = (char) br.read(); // 讀取單一字元
String line = br.readLine(); // 讀取整行字串
Scanner scanner = new Scanner(System.in);
// next() 以空白為分隔符,nextLine() 以換行符為分隔符
if (scanner.hasNextInt()) {
int num = scanner.nextInt();
}
next() vs nextLine() 差異:next() 會自動忽略前導空白,遇空白結束;nextLine() 可獲取包含空白的完整行。
// 寫入位元組
byte[] data = {11, 22, 33, 55, 66};
try (OutputStream os = new FileOutputStream("F:\\sql_text\\department.txt")) {
for (byte b : data) os.write(b);
}
// 讀取位元組
try (InputStream is = new FileInputStream("F:\\sql_text\\department.txt")) {
int size = is.available();
for (int i = 0; i < size; i++) System.out.print(is.read());
}
// 寫入指定編碼
File f = new File("F:\\sql_text\\department.txt");
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(f), "UTF-8")) {
writer.append("中文輸入").append("\r\n").append("English");
}
// 讀取指定編碼
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(f), "UTF-8")) {
StringBuffer sb = new StringBuffer();
while (reader.ready()) sb.append((char) reader.read());
System.out.println(sb.toString());
}
IOException、ClassNotFoundExceptionNullPointerException、ArrayIndexOutOfBoundsExceptionOutOfMemoryError、StackOverflowErrortry {
// 風險程式碼
} catch (ExceptionType1 e1) {
// 處理異常 1
} catch (ExceptionType2 e2) {
// 處理異常 2
} finally {
// 清理資源,必定執行
}
// 受檢異常
class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) { this.amount = amount; }
public double getAmount() { return amount; }
}
// 使用場景:銀行提款
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= balance) balance -= amount;
else throw new InsufficientFundsException(amount - balance);
}
java.io.Serializable 介面transient// Employee.java
public class Employee implements Serializable {
public String name;
public String address;
public transient int SSN; // 不序列化
public int number;
}
// 序列化
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.ser"))) {
Employee e = new Employee();
e.name = "Nick"; e.address = "Beijing"; e.SSN = 630571017; e.number = 18;
out.writeObject(e);
}
// 反序列化
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.ser"))) {
Employee e = (Employee) in.readObject();
// SSN 將為 0,因為 transient 不序列化
}
下載 MySQL Connector/J 驅動包,專案中引入 JAR。Maven 依賴:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
public class MySQLDemo {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC";
private static final String USER = "root";
private static final String PASS = "password";
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name FROM user")) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
最佳實踐:使用 try-with-resources 自動關閉資源,採用 PreparedStatement 防止 SQL 注入,連線池管理連線生命週期。

public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(9999);
}
public void run() {
while (true) {
try (Socket client = serverSocket.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
DataOutputStream out = new DataOutputStream(client.getOutputStream())) {
System.out.println("Client connected: " + client.getRemoteSocketAddress());
System.out.println("Received: " + in.readUTF());
out.writeUTF("Server reply: " + client.getLocalSocketAddress());
} catch (SocketTimeoutException e) {
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) throws IOException {
new GreetingServer(Integer.parseInt(args[0])).start();
}
}
public class GreetingClient {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream())) {
out.writeUTF("Hello from " + socket.getLocalSocketAddress());
System.out.println("Server says: " + in.readUTF());
}
}
}
| 類別 | 常用方法 | 說明 |
|---|---|---|
| ServerSocket | accept() | 阻塞等待客戶端連線 |
| Socket | getInputStream() / getOutputStream() | 獲取雙向通訊流 |
| InetAddress | getByName() / getLocalHost() | IP 位址解析 |
掌握 Java I/O 流體系、異常處理機制、物件序列化、JDBC 資料庫操作與 Socket 網路程式設計,是成為合格 Java 後端工程師的必經之路。建議開發者在理解原理基礎上,多實作、多重構,逐步建立起自己的技術知識體系。