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

Java I/O 全面指南:字符流與字節流核心類、實戰代碼與性能選型

     編輯:Java 綜合教學

Java I/O 全面指南:字符流與字節流核心類、實戰代碼與性能選型

Java I/O 以流為核心抽象,本文系統梳理類結構、字符/字節流區別、核心 API 及文件操作實戰代碼。

I/O 類結構與核心概念

Java I/O類結構圖:InputStream/OutputStream字節流、Reader/Writer字符流

字符流 vs 字節流 核心區別

維度字節流字符流
處理單位字節字符 (經編碼表轉換)
適用數據所有類型 (圖片、視頻、音頻、二進制)純文本數據
緩衝區直接操作文件,無緩衝使用緩衝區操作
核心類InputStream/OutputStreamReader/Writer

選型原則:純文本優先字符流,其他場景用字節流

字符流實戰:FileReader/Writer 與 BufferedReader/Writer

字符流類結構圖

讀取文件最佳實踐

public void readFileByBufferedReader(String path) {
    File file = new File(path);
    if (file.isFile()) {
        try (FileReader fr = new FileReader(file);
             BufferedReader br = new BufferedReader(fr)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) { e.printStackTrace(); }
    }
}

關鍵點:try-with-resources 自動關閉資源 (Java 7+),readLine() 按行讀取高效便捷。

寫入文件最佳實踐

public void writeFileByBufferedWriter(String path) {
    File file = new File(path);
    if (file.isFile()) {
        try (FileWriter fw = new FileWriter(file, true);  // true=追加模式
             BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write("新增行內容\r\n");
            bw.newLine(); // 跨平台換行
            bw.flush();   // 強制刷新緩衝區
        } catch (IOException e) { e.printStackTrace(); }
    }
}

字節流實戰:FileInputStream/OutputStream

字節流類結構圖

讀取二進制文件

public void readFileByFileInputStream(String path) {
    try (FileInputStream fis = new FileInputStream(path)) {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            System.out.print(new String(buffer, 0, len)); // 指定有效長度
        }
    } catch (IOException e) { e.printStackTrace(); }
}

寫入二進制文件

public void writeFileByFileOutputStream(String path) {
    try (FileOutputStream fos = new FileOutputStream(path, true)) {
        String str = "FileOutputStream 寫入內容\r\n";
        fos.write(str.getBytes());
        fos.flush();
    } catch (IOException e) { e.printStackTrace(); }
}

finally 塊關鍵特性補充

  1. 無論是否異常都會執行
  2. try/catch 中有 return 仍執行 finally
  3. 返回值在 finally 前確定,finally 不可改變返回值
  4. 避免在 finally 中使用 return 導致異常吞沒

性能優化建議

  • 大文件複製:FileChannel.transferTo() 零拷貝
  • 頻繁讀寫:必須使用 Buffered 包裝類
  • 字符編碼:顯式指定 StandardCharsets.UTF_8 避免平台差異
  • 資源管理:Java 7+ 必用 try-with-resources

掌握流體系架構、編碼轉換機制、緩衝策略,是高效處理文件、網絡、壓縮等 I/O 密集型任務的基石。

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