概述
基本概念
- 輸入流:從硬盤到內存。(輸入又叫做 讀 read)
- 輸出流:從內存到硬盤。(輸出又叫做 寫 write)
- 字節流:一次讀取一個字節。適合非文本數據,它是萬能的,啥都能讀。
- 字符流:一次讀取一個字符。只適合讀取普通文本。
Java 中所有 IO 流中凡是以 Stream 結尾的都是字節流。凡是 Read 和 Writer 結尾的都是字符流。
體系結構
- 四大頭領(都是抽象類)
- InputStream
- OutStream
- Reader
- Writer
- File 相關的
- FileInputStream
- FileOutputStream
- FileReader
- FileWriter
- 緩沖流相關的
- BufferedInputStream
- BufferedOutputStream
- BufferedReader
- BufferedWriter
- 轉換流相關的
- InputStreamReader
- OutputStreamWriter
- 打印流相關的
- PrintStream
- PirntWriter
- 對象相關的
- ObjectInputStream
- ObjectOutputStream
- 數據類型相關的
- DataInputStream
- DataOutputStream
- 字節數組相關的
- ByteArrayInputStream
- ByteArrayOutputStream
- 壓縮解壓縮相關的
- GZIPInputStream
- GZIPOutputStream
- 線程相關的
- PipedInputStream
- PipedOutputStream
- 所有的流都實現了 Closeable 接口,都有 close() 方法,流用完要關閉。
- 所有的輸出流都實現了 Flushable 接口,都有 flush() 方法,flush 方法的作用是將緩存清空,全部寫出。
各種流的詳解
文件輸入輸出流 FileInputStream & FileOutputStream
FileInputStream
-
構造方法之一
FileInputStream (Stirng s)
-
普通方法
read()
返回文件中的第一個字節本身(ascii碼),讀一次往后移一個字節,如果讀不到任何數據就返回 -1read(byte[] b)
一次最多可以讀取到 b.length 個字節,返回值是讀取到的字節數量,如果每讀到任何數據就返回 -1read(byte[] b, int off, int len)
一次最多讀 len 個字節,并且從 byte 數組的第 off 位置開始存skip(long n)
跳過流中的 n 個字節后讀取available()
返回流中剩余的字節數
FileOutputStream
- 構造方法
FileOutputStream(String name, boolean append)
如果 append == false,則在第一次建立流時將源文件的內容清空
如果 append == true,則通過追加的方式寫入 - 普通方法
FileReader & FileWriter 與 FileInputStream & FileOutputStream使用方式類似,只是字符流的使用 char[ ] 存儲,還可以直接寫入字符串
// FileWriter 測試代碼
try (FileWriter fw = new FileWriter("C:\\Users\\win\\Desktop\\111.txt")) {fw.write("hello");fw.write("world", 1, 2);fw.write("hello".toCharArray(), 0, 2);fw.write("hello".toCharArray());} catch (IOException e) {throw new RuntimeException(e);
}
try-with-resource
下面這種形式的流是 try-with-resource 語法,不需要手動寫 close() 了,資源會自動關閉。因為所有的流都實現了 Closeable 接口的父接口 AutoCloseable 接口,都可以使用 try-with-resource 語法。
try(流1;流2){操作代碼;
}catch(Exception e){}
注:本文章源于學習動力節點老杜
的java教程視頻后的筆記整理,方便自己復習的同時,也希望能給csdn的朋友們提供一點幫助。