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

Java IO 流體系總結:從 File 類到字節/字符流完整圖譜

     編輯:Java 綜合教學

一、File 類:文件系統抽象路徑

java.io.File 類代表文件系統中的文件或目錄路徑(不可直接讀寫文件內容)。核心能力:

  • 路徑操作:獲取絕對路徑、父目錄、文件名、擴展名
  • 屬性查詢:exists()、isFile()、isDirectory()、length()、lastModified()
  • 目錄操作:mkdir()、mkdirs()、list()、listFiles()
  • 文件操作:createNewFile()、delete()、renameTo()

跨平台路徑分隔符最佳實踐

// 錯誤寫法:硬編碼分隔符
File f1 = new File("D:/data/test.txt"); // Windows 可行,Linux 失敗

// 正確寫法:使用 File.separator 或 Paths.get()
File f2 = new File("." + File.separator + "aa.txt"); // 當前目錄下 aa.txt
// 或 Java 7+ 推薦
Path path = Paths.get(".", "aa.txt"); // 自動處理分隔符
File f3 = path.toFile();

文件創建完整示例

File file = new File("." + File.separator + "aa.txt");
System.out.println("文件是否存在: " + file.exists());

if (!file.exists()) {
    try {
        boolean created = file.createNewFile();
        System.out.println("創建結果: " + created);
    } catch (IOException e) {
        e.printStackTrace(); // 生產環境請使用 SLF4J 記錄
    }
}

二、IO 流分類總覽

Java IO 按數據單位分為字節流(8-bit)和字符流(16-bit Unicode);按流向分為輸入流(讀)和輸出流(寫)。

分類抽象基類文件操作實現緩衝增強轉換橋接
字節流InputStream / OutputStreamFileInputStream / FileOutputStreamBufferedInputStream / BufferedOutputStream—
字符流Reader / WriterFileReader / FileWriterBufferedReader / BufferedWriterInputStreamReader / OutputStreamWriter

三、核心流使用模式

1. 字節流複製文件(圖片/視頻/二進制)

public static void copyFileByte(String src, String dest) {
    try (FileInputStream fis = new FileInputStream(src);
         FileOutputStream fos = new FileOutputStream(dest);
         BufferedInputStream bis = new BufferedInputStream(fis);
         BufferedOutputStream bos = new BufferedOutputStream(fos)) {
        
        byte[] buffer = new byte[8192]; // 8KB 緩衝區
        int len;
        while ((len = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.flush();
    } catch (IOException e) { e.printStackTrace(); }
}

2. 字符流讀寫文本文件(指定編碼)

public static void copyFileChar(String src, String dest, String charset) {
    try (BufferedReader br = new BufferedReader(
            new InputStreamReader(new FileInputStream(src), charset));
         BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(dest), charset))) {
        
        String line;
        while ((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine(); // 跨平台換行
        }
    } catch (IOException e) { e.printStackTrace(); }
}

3. 緩衝流特有方法

  • BufferedReader.readLine():按行讀取文本,返回不含換行符的字符串
  • BufferedWriter.newLine():寫入系統默認行分隔符
  • BufferedInputStream.mark()/reset():支持標記重讀

四、轉換流:字節↔字符橋樑

InputStreamReader:字節流→字符流(解碼)
OutputStreamWriter:字符流→字節流(編碼)

// 核心構造方法:指定字符集,避免平台默認編碼導致亂碼
Reader reader = new InputStreamReader(new FileInputStream("data.txt"), "UTF-8");
Writer writer = new OutputStreamWriter(new FileOutputStream("out.txt"), "UTF-8");

五、Java 7+ try-with-resources 自動資源管理

所有實現 AutoCloseable 的流對象均可在 try 括號中聲明,編譯器自動生成 finally 關閉代碼,彻底解決資源洩漏。

// 等價於手動 finally close(),但更簡潔、異常安全
try (FileInputStream fis = new FileInputStream("in.txt");
     FileOutputStream fos = new FileOutputStream("out.txt")) {
    // 業務代碼
} // 編譯器自動插入 fis.close(); fos.close();

六、常見面試考點

  1. 字節流 vs 字符流:字節流處理原始二進制(圖片、視頻、對象序列化),字符流處理文本(自動編碼轉換)
  2. 緩衝流作用:減少系統調用次數,提升 IO 效率(內存緩衝區默認 8KB)
  3. 裝飾者模式:Java IO 大量使用裝飾者模式(如 BufferedInputStream 包裝 FileInputStream)
  4. 序列化:ObjectOutputStream/ObjectInputStream 實現對象持久化,需實現 Serializable
  5. NIO.2 (Java 7+):Files、Paths、Path API 更現代、支持符號鏈接、屬性讀取、異步 IO

七、最佳實踐清單

  • ✅ 文本文件必須指定編碼(UTF-8 推薦)
  • ✅ 大文件複製必須使用緩衝流
  • ✅ 所有流操作使用 try-with-resources
  • ✅ 區分字節/字符流場景,避免亂碼
  • ✅ 高併發場景考慮 NIO/Netty 零拷貝

記住:File 類只管路徑元數據,不管內容;讀寫內容必須用流。字節流是基礎,字符流是字節流經過編碼轉換的包裝。緩衝流是性能優化利器,裝飾者模式讓組合靈活無限。

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