解決開發(fā)中使用哪個流對象的問題
1.明確數據源,數據匯(數據目的)
其實就是在明確要使用的io體系 InputStream OutputStream Reader Writer
操作的是源 那么就需要讀取
操作的是匯 那么就需要寫入
2.操作的數據 是否是純文本數據 是為字符流 否在字節(jié)流
是 并且是源 Reader
是 并且是目的 Writer
3.明確要操作的具體設備 每個設備都有對應的流對象
源:
硬盤 能操作文件的流對象都是 File開頭
鍵盤 System.in
內存 數組
網絡 socket流
目的:
硬盤 能操作文件的流對象都是 File開頭
內存 數組
網絡 System.out
顯示器 socket流
4.額外功能
緩沖區(qū) Buffered開頭
轉換流
需求1: 通過鍵盤錄入數據 并保存到一個文件中
明確1:有源 有目的嗎
源使用 InPutStream Reader
目的使用 OutPutStream Writer
明確2: 是純文本數據嗎 是
源 Reader
目的 Writer
明確3:具體設備
源設備System.in
目的設備硬盤
IuputStream is=System.in
FileWriter fw=new FileWriter("a.txt");
將讀取的字節(jié)存儲到數組中 read(byte[])
將字節(jié)數組轉化成字符串
通過fw.write(String)寫入文件中
麻煩 明確源是Reader
明確4:需要功能嗎?
需要字節(jié)轉字符 InputStreamReader
InputStreamReader isr= new InputStreamReader(System.in);
需要額外功能嗎?
需要(out帶緩存需要刷新)
BufferedReader bufr =new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bwfw=new BufferedWriter(new FileWriter("a.txt"));
readLine();
bufw.write(); bufw.flush();
需求2:讀取文本文件中的數據 將其打印到控制臺上
明確1:有源 有目的
源:InputStream Reader
目的 OutputStream Writer
明確2:是純文本
源:Reader
目的:Writer
明確3:具體設備
源設備 :硬盤 File
目的設備:顯示器 System.out
FileReader fr=new FileReader("a.txt");
OutputStream ops=System.out;
fr讀取數據到數組中。將數組文件打印到顯示器
源是字符數據 所以通過字符流操作 通過字符轉成字節(jié)流 給顯示器
明確4:額外功能
字符轉換到字節(jié)
FileReader fr=new FileReader("a.txt");
OutputStreamWriter osw=new OutputStreamWriter(System.in);
高效
BufferedReader bufr=new BufferedReader(new FileReader("a.txt"));
BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(System.out));
讀取一行數據
寫入一行數據
轉換流 InputStreamReader OutputStreamWriter