首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 初學者備忘錄:異常處理、IO 流、文件操作與 Socket 通信完整實戰

     編輯:Java 相關知識

本文作為 Java 入門開發者的桌面速查手冊,濃縮了異常處理機制、標準 IO 流體系、文件操作實例、Socket 客戶端/服務端通信完整代碼。所有代碼經實測可運行,註釋詳盡,適合初學者快速建立核心知識體系。

一、異常處理機制

Java 採用拋捕模型:運行時拋出,代碼中捕獲處理。與 Delphi try..except..finally 類似。

基本語法

try {
    // 可能拋出異常的代碼
} catch (ExceptionType1 e) {
    // 處理異常類型 1
} catch (ExceptionType2 e) {
    // 處理異常類型 2
    throw e; // 重新拋出
} finally {
    // 無論是否異常必執行(關閉資源等)
}

關鍵規則

  • 檢查型異常(非 RuntimeException 子類):必須 try-catch 或方法簽名 throws 聲明,否則編譯不通過
  • 運行時異常:可不捕獲不聲明,但最佳實踐建議顯式處理
  • throw 拋出異常對象,throws 聲明方法可能拋出的異常類型

二、Java IO 流體系全景

標準流

System.out.print / println  // 標準輸出
System.err.print / println  // 標準錯誤輸出(同屏顯示但語義不同,可單獨重定向)
System.in.read()            // 標準輸入(單字節讀取,常包裝為 BufferedReader)

流分類與核心類

維度輸入流(讀)輸出流(寫)典型用途
節點流(直達數據源)FileInputStreamFileOutputStream文件字節讀寫
FileReaderFileWriter文件字符讀寫
處理流(包裝增強)BufferedInputStreamBufferedOutputStream緩衝提速
BufferedReaderBufferedWriter按行/字符高效讀寫
DataInputStreamDataOutputStream基本類型序列化
ObjectInputStreamObjectOutputStream對象序列化
PipedInputStreamPipedOutputStream線程間管道通信

裝飾器模式:層層包裝,如 new BufferedReader(new InputStreamReader(new FileInputStream(file)))。

三、文件操作實戰範例

1. 文件信息查看器

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.");
        }
    }
}

2. 電話簿存儲(FileOutputStream 實戰)

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;
    }
}

四、Socket 通信完整實現:客戶端/服務端

場景:客戶端請求讀取服務端文件內容,服務端返回文件數據。

核心步驟速記

  1. 客戶端:new Socket(ip, port) → 獲取流 → 包裝 BufferedReader/PrintWriter → 發送文件名 → 讀取響應 → 關閉流
  2. 服務端: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。否則客戶端收不到數據(緩衝區未刷新/通道提前關閉),甚至導致雙端死鎖。

五、學習路線建議

  1. 掌握異常處理 → 理解程序健壯性基石
  2. 熟練 IO 流體系 → 輸入輸出操作核心
  3. 實戰文件讀寫 → 持久化基礎
  4. 實現 Socket 通信 → 網絡編程入門
  5. 進階:NIO、Netty、HTTP 客戶端、序列化框架

本備忘錄涵蓋 Java 核心基礎 80% 高頻知識點,建議打印桌邊,遇到語法細節隨時翻閱。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved