java.io 基於流(Stream)串行化讀寫,API 簡單但效率受限於頻繁系統調用java.nio 基於通道與緩衝區,支援內存映射、零拷貝、非阻塞 IO,高吞吐場景首選| 字節流 | 字符流 | 區別 |
|---|---|---|
InputStream/OutputStream | Reader/Writer | 字符流自動處理編碼轉換(Unicode↔本地編碼) |
兩者成對出現:FileInputStream ↔ FileReader、BufferedInputStream ↔ BufferedReader。
核心類繼承關係:
FileInputStream、ByteArrayInputStream、PipedInputStreamFilterInputStream):BufferedInputStream、DataInputStream、GZIPInputStream、ObjectInputStream
// 經典嵌套寫法
InputStream in = new BufferedInputStream(
new FileInputStream("C:\\log.txt")
);
// 或分步構建(便於調試)
FileInputStream fis = new FileInputStream("C:\\log.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
同理,輸出流組合:new BufferedOutputStream(new FileOutputStream("out.dat"))。
FileChannel、SocketChannel、ServerSocketChannelByteBuffer、CharBuffer 等,支援 flip()/compact() 狀態切換OP_READ/OP_WRITE/OP_ACCEPT 事件
FileChannel in = FileChannel.open(Paths.get("big.dat"), StandardOpenOption.READ);
FileChannel out = FileChannel.open(Paths.get("copy.dat"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
in.transferTo(0, in.size(), out); // 內核態直接傳輸,無用戶態拷貝
java.io 裝飾器組合邏輯InputStreamReader、Charset)Buffer 狀態機、Selector 事件循環、FileChannel 內存映射