JAVA IO流幾個實用流對象
這段時間相繼看到幾個當初java基礎掌握不太熟悉的io類,所以專門找資料複習了一下這幾個類。
它們是:
RandomAccessFile // 隨機讀寫流
DataInputStream DataOutputStream // 數據讀取/寫入流
ByteArrayInputStream BateArrayOutputStream // 字節數組讀取/寫入流
CharArrayReader CharArrayWriter // 字符數組讀取/寫入流
StringReader StringWriter // 字符串讀取/寫入流
RandomAccessFile: 隨機讀寫流
- 該類不存在於IO體系中,而是直接繼承自Object
- 但此類存在於IO包中,因爲它具備讀和寫的功能
- 內部封裝了一個數組,通過指針對數組的元素進行操作
- 可以通過getFilePointer獲取指針位置
- 可以通過seek改變指針位置
- 操作文件可以指定模式
r/w/rw
- 可以直接寫入到硬盤,不經過硬盤的緩存
- 如果模式爲只讀 r。不會創建文件。會去讀取一個已存在文件,如果該文件不存在,則會出現異常。
- 如果模式rw。操作的文件不存在,會自動創建。如果存則不會覆蓋。
- 多線程下載時,可以用此類來完成分段寫入
DataInputStream DataOutputStream 數據讀取/寫入流
- 可以對基本數據類型進行讀和寫的操作
- 常用方法有: readInt/writeInt readBoolean/writeBoolean等
//read demo
private static void readData() throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream(file));
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
System.out.println(dis.readDouble());
}
//write demo
private static void writeData() throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
dos.writeInt(256);
dos.writeBoolean(false);
dos.writeDouble(3.1415926);
}
數組寫入/讀取流
ByteArrayInputStream BateArrayOutputStream 字節數組讀取/寫入流`
CharArrayReader CharArrayWriter 字符數組讀取/寫入流
StringReader StringWriter 字符串讀取/寫入流
- 對內存進行寫入和讀取操作的流對象
- 用流的讀寫思想來操作數組(數據)。