FileInputStream 詳解與記憶方法
一、FileInputStream 核心概念
FileInputStream
?是 Java 中用于從文件讀取原始字節的類,繼承自?InputStream
?抽象類。
1. 核心特點
特性 | 說明 |
---|---|
繼承關系 | InputStream ?→?FileInputStream |
數據單位 | 字節(8bit) |
用途 | 讀取二進制文件(如圖片、音頻、PDF等) |
是否緩沖 | 默認無緩沖(需配合?BufferedInputStream ?使用) |
線程安全 | 否 |
2. 構造方法
java
// 1. 通過文件路徑創建
FileInputStream fis = new FileInputStream("test.txt");// 2. 通過File對象創建
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);// 3. 通過文件描述符創建(高級用法)
FileDescriptor fd = new FileDescriptor();
FileInputStream fis = new FileInputStream(fd);
3. 核心方法
方法 | 作用 |
---|---|
int read() | 讀取單個字節(返回0-255,-1表示結束),調用一次read()方法則讀取一個字節,返回讀到的字節本身。(例如,信息為a,則返回一個97),如果讀不到任何數據則返回-1 |
int read(byte[] b) | 讀取字節到數組,返回實際讀取的字節數(一次最多讀取到b.length個字節) |
int read(byte[] b, int off, int len) | 從偏移量off開始讀取len個字節到數組 |
long skip(long n) | 跳過n個字節 |
void close() | 關閉流 |
FileChannel getChannel() | 獲取關聯的FileChannel(NIO相關) |
int? ? available()? ? ? | 返回預估計流當中剩余的字節數量(意思就是:還剩下幾個字節沒有讀取) |
二、使用示例
1. 基礎讀取文件
java
try (FileInputStream fis = new FileInputStream("data.bin")) {int data;while ((data = fis.read()) != -1) { // 每次讀取1字節System.out.print((char) data); // 轉為字符輸出(僅適用于文本)}
} // try-with-resources自動關閉流
2. 高效讀取(緩沖區)
java
try (FileInputStream fis = new FileInputStream("largefile.bin");BufferedInputStream bis = new BufferedInputStream(fis)) { // 添加緩沖byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = bis.read(buffer)) != -1) {// 處理buffer中的數據}
}
3. 讀取到字節數組
java
File file = new File("data.bin");
byte[] fileData = new byte[(int) file.length()];
try (FileInputStream fis = new FileInputStream(file)) {fis.read(fileData); // 一次性讀取全部內容
}
三、記憶技巧
1. 名稱解析法
"File + Input + Stream"
File:操作文件
Input:輸入(讀取)
Stream:字節流
2. 對比記憶法
對比類 | 方向 | 數據單位 | 典型用途 |
---|---|---|---|
FileInputStream | 讀取 | 字節 | 圖片、壓縮包等二進制文件 |
FileOutputStream | 寫入 | 字節 | 文件下載、數據存儲 |
FileReader | 讀取 | 字符 | 文本文件(自動處理編碼) |
3. 使用場景聯想
-
圖片處理:
FileInputStream
?+?ImageIO.read()
-
文件復制:
FileInputStream
?+?FileOutputStream
-
加密解密:讀取原始字節后進行加密運算
4. 常見誤區提醒
??錯誤用法:直接讀取文本文件(可能亂碼)
??正確做法:文本文件應使用?FileReader
?或?InputStreamReader
四、面試高頻問題
1. FileInputStream 和 BufferedInputStream 的區別?
-
FileInputStream:每次
read()
直接訪問磁盤,性能低 -
BufferedInputStream:內置緩沖區(默認8KB),減少磁盤IO次數
2. 為什么讀取文件要用 try-with-resources?
-
自動關閉資源:避免忘記調用
close()
導致文件句柄泄漏 -
代碼簡潔:不需要手動寫
finally
塊
3. 如何高效讀取大文件?
java
// 方案1:使用緩沖流
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("large.bin"))) {byte[] buffer = new byte[8192]; // 8KB緩沖區while (bis.read(buffer) != -1) {// 處理數據}
}// 方案2:使用NIO的FileChannel(超大文件更高效)
4. read() 方法返回值的含義?
-
返回int:0-255表示字節值,-1表示文件結束
-
注意:必須用int接收,byte會無法區分-1和255
五、總結圖示
mermaid
flowchart TDA[FileInputStream] --> B[讀取二進制文件]A --> C[核心方法: read/skip/close]A --> D[需配合緩沖流提升性能]B --> E[圖片/音頻/PDF等]D --> F[BufferedInputStream]
一句話總結:
"FileInputStream讀字節,無緩沖性能低,文本文件別用它,記得關閉保安全"