標籤:
一、流的分類
1. 按資料流動方向:
- 輸入資料流:只能從中讀取位元組資料,而不能向其寫出資料
- 輸出資料流:只能向其寫入位元組資料,而不能從中讀取資料
2. 按照流的資料類型:
- 位元組流:用於處理位元組資料,一次讀入或讀出是8位二進位。
- 字元流:用於處理Unicode字元資料,一次讀入或讀出是16位二進位。
3.按照實現功能不同可以分為:
- 節點流(低級流):從/向一個特定的IO裝置讀/寫資料的流。
- 處理流(進階流):對已存在的流進行串連和封裝的流。
二:java中io中常用的流
1.對檔案進行操作:
FileInputStream(位元組輸入資料流),FileOutputStream(位元組輸出資料流),FileReader(字元輸入資料流),FileWriter(字元輸出資料流)
2.對管道進行操作:
PipedInputStream(位元組輸入資料流),PipedOutStream(位元組輸出資料流),PipedReader(字元輸入資料流),PipedWriter(字元輸出資料流)
3.位元組/字元數組:
ByteArrayInputStream,ByteArrayOutputStream,CharArrayReader,CharArrayWriter是在記憶體中開闢了一個位元組或字元數組。
4.轉化流:
InputStreamReader,OutputStreamWriter,把位元組轉化成字元。
5.資料流:
DataInputStream,DataOutputStream。
6.Buffered緩衝流:
BufferedInputStream,BufferedOutputStream,BufferedReader,BufferedWriter,是帶緩衝區的處理流,緩衝區的作用的主要目的是:避免每次和硬碟打交道,提高資料訪問的效率。
7.列印流:
printStream,printWriter。
8.物件流程:
ObjectInputStream(還原序列化對象輸入資料流),ObjectOutputStream(序列化對象輸出資料流)。
三:舉例說明流的使用
/**
*匯入的標頭檔
*/
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;/** * 位元組輸入輸出資料流測試 * * @author Nikita * */public class IOTest { public static void main(String[] args) { StringBuffer buffer = new StringBuffer(); // 字串緩衝 /* 輸入資料流 */ InputStream in = null; try { // 1. 開啟輸入資料流 in = new FileInputStream("E:\\jg\\exercise.txt");//從一個路徑中開啟輸入資料流讀取內容 // 2. 讀取 byte[] b = new byte[1024 * 4]; int len = in.read(b); // 返回讀取到的位元組數,返回-1表示讀取到流結尾 while(len != -1){ buffer.append(new String(b, 0, len)); // 將讀取到的位元組解析為String追加到緩衝 len = in.read(b); } System.out.println(buffer.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 3. 釋放資源,關閉輸入資料流 if (in != null){ try { in.close();//調用close()方法 } catch (IOException e) { e.printStackTrace(); } } } /* 輸出資料流 */ OutputStream out = null; try { File file = new File("D:\\test\\demo\\test.txt");//將目標檔案路徑放置在一個指定位置寫入內容 if (!file.getParentFile().exists()){ // 檔案路徑不存在,則建立路徑中所有不存在的目錄 file.getParentFile().mkdirs(); } // 1. 開啟輸出資料流 out = new FileOutputStream(file); // 2. 寫 out.write(buffer.toString().getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 3. 釋放輸出資料流資源 if (out != null){ try {out.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
Java I/O流概念