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

Java IO 基礎入門(一):流模型、分類與文件讀寫實戰

     編輯:Java 相關知識

流的核心隱喻:數據的管道

  • 流:有序數據序列(位/字符),單向流動
  • 輸入流:外部設備/存儲 → 應用程序(讀取)
  • 輸出流:應用程序 → 外部設備/存儲(寫入)
  • 特點:順序訪問、設備無關性、可移植性

流的二維分類體系

維度分類基本類處理單位典型用途
按數據類型字節流InputStream / OutputStream8位字節圖片、視頻、二進制、網絡傳輸
字符流Reader / Writer16位字符 (UTF-16)文本文件、字符串處理、控制台
按流向輸入流InputStream / Reader-讀取數據源
輸出流OutputStream / Writer-寫入目標

File 類:路徑元數據操作(非流)

  • 關注文件屬性:路徑、大小、修改時間、權限、目錄結構
  • 不處理文件內容(那是流的事)
  • 跨平台路徑處理:File.separator、File.pathSeparator

實戰案例 1:鍵盤輸入 → 文件 → 控制台輸出

import java.io.*;

public class FileTest {
    public static void main(String[] args) {
        try {
            // 1. 鍵盤輸入流 (標準輸入)
            FileInputStream fis = new FileInputStream(FileDescriptor.in);
            // 2. 文件輸出流
            FileOutputStream fos = new FileOutputStream("d:\\myfile.txt");
            
            System.out.println("請輸入字符串,以 # 結束:");
            int ch;
            while ((ch = fis.read()) != '#') { // 讀取單字節
                fos.write(ch); // 寫入單字節
            }
            fis.close();
            fos.close();
            
            // 3. 文件輸入流讀回
            FileInputStream fi = new FileInputStream("d:\\myfile.txt");
            // 4. 控制台輸出流 (標準輸出)
            FileOutputStream fo = new FileOutputStream(FileDescriptor.out);
            
            int data;
            while (fi.available() > 0) { // 可用字節數
                data = fi.read();
                fo.write(data);
            }
            fi.close();
            fo.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到:" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

關鍵點:FileDescriptor.in/out 代表標準輸入輸出,available() 估算可讀字節,單字節讀寫效率低,教學用。

實戰案例 2:二進制圖片文件複製(字節數組緩衝)

import java.io.*;

public class ImageFileTest {
    public static void main(String[] args) throws IOException {
        FileInputStream fi = new FileInputStream("d:\\scenery.jpg");
        FileOutputStream fo = new FileOutputStream("d:\\copyScenery.jpg");
        
        // 一次性讀入內存(僅適合小文件)
        byte[] buffer = new byte[fi.available()];
        fi.read(buffer);  // 讀滿數組
        fo.write(buffer); // 寫入數組
        
        System.out.println("文件已複製並重命名");
        fi.close();
        fo.close();
    }
}

改進方向:大文件必須分塊讀寫(如 4KB/8KB 緩衝區),避免 OOM。

字節流與字符流轉換橋樑

// 字節流 → 字符流 (指定編碼)
InputStreamReader isr = new InputStreamReader(new FileInputStream("data.txt"), "UTF-8");
BufferedReader br = new BufferedReader(isr);

// 字符流 → 字節流 (指定編碼)
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("out.txt"), "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);

核心認知:InputStreamReader/OutputStreamWriter 是編碼轉換器,解決字節與字符邊界問題。

資源管理最佳實踐:Try-with-resources (Java 7+)

// 自動關閉資源,異常安全
try (FileInputStream fis = new FileInputStream("in.txt");
     FileOutputStream fos = new FileOutputStream("out.txt")) {
    byte[] buf = new byte[8192];
    int len;
    while ((len = fis.read(buf)) != -1) {
        fos.write(buf, 0, len);
    }
} // 編譯器自動生成 finally 關閉代碼

總結

Java IO 基石在於:流的單向性、字節/字符二元分類、裝飾者模式組合功能。掌握 File 與流的分工、字節字符轉換橋樑、緩衝區大小選擇、try-with-resources 资源安全,即可應對 90% 文件處理場景。

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