java IO系統採用裝飾器模式,用一些裝飾類來裝飾輸入輸出來,提供更強大的IO操作
FilterInputStream(FilterOutputStream)繼承自InputStream(Outputstream)
常用裝飾類(都繼承自FilterInputStream) 功能
DataInputStream(DataOutputStream) 讀寫基本類型即UTF
BufferedInputStream(BufferedOutputStream) 使用緩衝區
PrintStream繼承自Outputstream,用于格式化輸出到文本或控制台等
樣本:
package test;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/* * DataInputStream繼承自FilterInputStream(FilterInputStream繼承自InputStream) * 用來裝飾InputStream,提供可移植方式從流讀取基礎資料型別 (Elementary Data Type) * DataOutputStream繼承自FilterOutputStream(FilterOutputStream繼承自OutputStream) * 用來裝飾OutputStream,提供可移植方式向流寫入基礎資料型別 (Elementary Data Type) * DataInputStream/DataOutputStream可以實現資料的儲存與恢複 */public class DataInputStreamDemo {public static void main(String[] args) {DataOutputStream dataOutStream = null;try {dataOutStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("file/aa.data")));} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {// 寫入檔案dataOutStream.writeChar('a');dataOutStream.writeInt(3);dataOutStream.writeDouble(5.5);dataOutStream.writeFloat(3.2f);dataOutStream.writeUTF("nihaoma");dataOutStream.close();} catch (IOException e) {e.printStackTrace();}DataInputStream dataInputStream = null;try {dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream("file/aa.data")));} catch (FileNotFoundException e) {e.printStackTrace();}try {// 讀取檔案System.out.println(dataInputStream.readChar());System.out.println(dataInputStream.readInt());System.out.println(dataInputStream.readDouble());System.out.println(dataInputStream.readFloat());System.out.println(dataInputStream.readUTF());dataInputStream.close();} catch (IOException e) {e.printStackTrace();}}}
package test;import java.io.FileNotFoundException;import java.io.PrintStream;/* * 繼承自FilterOutputStream,其中DataOutputStream處理資料的儲存,PrintStream處理顯示 * 用于格式化列印 */public class PrintStreamDemo {public static void main(String[] args) throws FileNotFoundException {// 把資料視覺效果格式顯示到文字檔中PrintStream printStream = new PrintStream("file/test2.txt");printStream.println('a');printStream.println(2);printStream.println(3.2);printStream.println("liuhaifang");printStream.println("劉海房");// 可視化顯示到控制台printStream = new PrintStream(System.out);printStream.println("hello java");}}