本文作為 Java 入門開發者的桌面速查手冊,濃縮了異常處理機制、標準 IO 流體系、文件操作實例、Socket 客戶端/服務端通信完整代碼。所有代碼經實測可運行,註釋詳盡,適合初學者快速建立核心知識體系。
Java 採用拋捕模型:運行時拋出,代碼中捕獲處理。與 Delphi try..except..finally 類似。
try {
// 可能拋出異常的代碼
} catch (ExceptionType1 e) {
// 處理異常類型 1
} catch (ExceptionType2 e) {
// 處理異常類型 2
throw e; // 重新拋出
} finally {
// 無論是否異常必執行(關閉資源等)
}
try-catch 或方法簽名 throws 聲明,否則編譯不通過throw 拋出異常對象,throws 聲明方法可能拋出的異常類型System.out.print / println // 標準輸出
System.err.print / println // 標準錯誤輸出(同屏顯示但語義不同,可單獨重定向)
System.in.read() // 標準輸入(單字節讀取,常包裝為 BufferedReader)
| 維度 | 輸入流(讀) | 輸出流(寫) | 典型用途 |
|---|---|---|---|
| 節點流(直達數據源) | FileInputStream | FileOutputStream | 文件字節讀寫 |
| FileReader | FileWriter | 文件字符讀寫 | |
| 處理流(包裝增強) | BufferedInputStream | BufferedOutputStream | 緩衝提速 |
| BufferedReader | BufferedWriter | 按行/字符高效讀寫 | |
| DataInputStream | DataOutputStream | 基本類型序列化 | |
| ObjectInputStream | ObjectOutputStream | 對象序列化 | |
| PipedInputStream | PipedOutputStream | 線程間管道通信 |
裝飾器模式:層層包裝,如 new BufferedReader(new InputStreamReader(new FileInputStream(file)))。
import java.io.*;
public class FileInfo {
public static void main(String[] args) throws IOException {
if (args.length == 0) { System.out.println("no file given"); return; }
for (String arg : args) {
File f = new File(arg);
info(f);
}
}
static void info(File f) throws IOException {
System.out.println("Name: " + f.getName());
System.out.println("Path: " + f.getPath());
if (f.exists()) {
System.out.println("File exists.");
System.out.print(f.canRead() ? " and is Readable" : "");
System.out.print(f.canWrite() ? " and is Writable" : "");
System.out.println(". File is " + f.length() + " bytes.");
} else {
System.out.println("File does not exist.");
}
}
}
import java.io.*;
public class PhoneBook {
static FileOutputStream fos;
static final int LINE_LEN = 81;
public static void main(String[] args) throws IOException {
byte[] name = new byte[LINE_LEN];
byte[] phone = new byte[LINE_LEN];
fos = new FileOutputStream("phone.numbers");
while (true) {
System.err.println("Enter name ('done' to quit):");
readLine(name);
if ("done".equalsIgnoreCase(new String(name, 0, 0, 4))) break;
System.err.println("Enter phone:");
readLine(phone);
for (int i=0; phone[i]!=0; i++) fos.write(phone[i]);
fos.write(',');
for (int i=0; name[i]!=0; i++) fos.write(name[i]);
fos.write('\n');
}
fos.close();
}
static void readLine(byte[] line) throws IOException {
int i=0, b;
while (i < LINE_LEN-1 && (b=System.in.read()) != '\n') line[i++] = (byte)b;
line[i] = 0;
}
}
場景:客戶端請求讀取服務端文件內容,服務端返回文件數據。
new Socket(ip, port) → 獲取流 → 包裝 BufferedReader/PrintWriter → 發送文件名 → 讀取響應 → 關閉流new ServerSocket(port) → accept() 循環 → 獲取流 → 讀取文件名 → 讀取文件內容 → 寫回響應 → 先關 Writer 後關 Reader → 循環等待下一連接import java.io.*; import java.net.*;
public class RemoteFileClient {
String hostIp; int hostPort;
BufferedReader socketReader; PrintWriter socketWriter;
public RemoteFileClient(String ip, int port) { hostIp=ip; hostPort=port; }
public void setUpConnection() {
try {
Socket client = new Socket(hostIp, hostPort);
socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
socketWriter = new PrintWriter(client.getOutputStream());
} catch (UnknownHostException e) { System.out.println("Unknown host: " + hostIp); }
catch (IOException e) { System.out.println("IO Error: " + e); }
}
public String getFile(String fileName) {
StringBuffer buf = new StringBuffer();
try {
socketWriter.println(fileName); socketWriter.flush();
String line;
while ((line = socketReader.readLine()) != null) buf.append(line).append("\n");
} catch (IOException e) { System.out.println("Read error: " + e); }
return buf.toString();
}
public void tearDownConnection() {
try { socketWriter.close(); socketReader.close(); } catch (IOException e) { System.out.println("Close error: " + e); }
}
public static void main(String[] args) {
RemoteFileClient c = new RemoteFileClient("127.0.0.1", 3000);
c.setUpConnection();
System.out.println(c.getFile("RemoteFile.txt"));
c.tearDownConnection();
}
}
import java.io.*; import java.net.*;
public class RemoteFileServer {
int listenPort = 3000;
public void acceptConnections() {
try {
ServerSocket server = new ServerSocket(listenPort);
Socket incoming;
while (true) {
incoming = server.accept();
handleConnection(incoming);
}
} catch (BindException e) { System.out.println("Port bind failed: " + listenPort); }
catch (IOException e) { System.out.println("ServerSocket error: " + e); }
}
void handleConnection(Socket conn) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
PrintWriter out = new PrintWriter(conn.getOutputStream());
String filePath = in.readLine();
BufferedReader fileIn = new BufferedReader(new FileReader(filePath));
String line;
while ((line = fileIn.readLine()) != null) out.println(line);
fileIn.close(); out.close(); in.close(); // 順序關鍵!
} catch (Exception e) { System.out.println("Handle error: " + e); }
}
public static void main(String[] args) {
new RemoteFileServer().acceptConnections();
}
}
必須先關閉 OutputStream/Writer,再關閉 InputStream/Reader。否則客戶端收不到數據(緩衝區未刷新/通道提前關閉),甚至導致雙端死鎖。
本備忘錄涵蓋 Java 核心基礎 80% 高頻知識點,建議打印桌邊,遇到語法細節隨時翻閱。