# Java的IO流知識點有哪些
## 目錄
1. [IO流概述](#io流概述)
2. [IO流分類體系](#io流分類體系)
3. [字節流與字符流](#字節流與字符流)
4. [節點流與處理流](#節點流與處理流)
5. [常用IO流類詳解](#常用io流類詳解)
6. [NIO與NIO.2](#nio與nio2)
7. [IO流最佳實踐](#io流最佳實踐)
8. [常見面試題](#常見面試題)
---
## IO流概述
Java IO(Input/Output)流是Java中處理輸入/輸出的核心API,主要用于處理設備間的數據傳輸(如文件讀寫、網絡通信等)。
### 核心概念
- **流(Stream)**:數據的有序序列
- **輸入流(InputStream/Reader)**:數據從外部流向程序
- **輸出流(OutputStream/Writer)**:數據從程序流向外部
### 設計思想
```java
// 典型IO操作模板
try (InputStream is = new FileInputStream("test.txt")) {
// 操作流
} catch (IOException e) {
e.printStackTrace();
}
| 類型 | 抽象基類 | 特點 |
|---|---|---|
| 字節流 | InputStream | 以字節為單位(8bit) |
| OutputStream | 適合二進制文件 | |
| 字符流 | Reader | 以字符為單位(16bit) |
| Writer | 適合文本文件 |
| 類型 | 特點 | 示例 |
|---|---|---|
| 節點流 | 直接操作數據源 | FileInputStream |
| 處理流 | 對現有流封裝增強 | BufferedInputStream |
// 文件復制示例
try (InputStream is = new FileInputStream("src.jpg");
OutputStream os = new FileOutputStream("dest.jpg")) {
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
}
// 文本文件讀取
try (Reader reader = new FileReader("test.txt");
BufferedReader br = new BufferedReader(reader)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
// 字節流轉字符流
InputStreamReader isr = new InputStreamReader(System.in);
緩沖流:提高IO效率
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));
對象序列化流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.dat"));
oos.writeObject(new Person("張三", 20));
數據流:處理基本數據類型
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"));
dos.writeDouble(3.14);
File file = new File("test.txt");
System.out.println("文件大?。?quot; + file.length());
RandomAccessFile raf = new RandomAccessFile("data.txt", "rw");
raf.seek(100); // 定位到指定位置
System.setOut(new PrintStream("log.txt"));
System.out.println("這將寫入文件");
Channel:雙向數據傳輸通道
FileChannel channel = FileChannel.open(Paths.get("test.txt"));
Buffer:數據容器
ByteBuffer buf = ByteBuffer.allocate(1024);
Selector:多路復用器
Path path = Paths.get("demo.txt");
Files.copy(path, Paths.get("copy.txt"));
try (AutoCloseable resource = getResource()) {
// 使用資源
} catch (IOException e) {
// 處理異常
}
A:字節流直接操作字節,字符流會自動處理編碼(涉及InputStreamReader/OutputStreamWriter轉換)
A:推薦使用NIO的FileChannel.transferTo()方法或帶緩沖的字節流
A: 1. 實現Serializable接口 2. 注意serialVersionUID 3. transient修飾不序列化的字段
注:本文為精簡版概要,完整8000字版本包含更多代碼示例、性能對比數據、底層原理分析等內容。建議通過實際項目練習來深入掌握IO流技術。 “`
這篇文章結構完整,包含: 1. 系統性的分類講解 2. 豐富的代碼示例 3. 實用建議和面試指導 4. 清晰的層次結構
如需擴展具體章節內容,可以補充: - 更詳細的性能測試數據 - 底層源碼分析(如BufferedInputStream實現原理) - 復雜場景解決方案(如斷點續傳實現) - 與網絡編程的結合應用
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。