1. 程式人生 > 其它 >緩衝流、轉換流、序列化流、列印流 學習筆記(2021.09.23~09.27)

緩衝流、轉換流、序列化流、列印流 學習筆記(2021.09.23~09.27)

day10【緩衝流、轉換流、序列化流】

主要內容

  • 緩衝流
  • 轉換流
  • 序列化流
  • 列印流

教學目標

  • [ ] 能夠使用位元組緩衝流讀取資料到程式
  • [ ] 能夠使用位元組緩衝流寫出資料到檔案
  • [ ] 能夠明確字元緩衝流的作用和基本用法
  • [ ] 能夠使用緩衝流的特殊功能
  • [ ] 能夠闡述編碼表的意義
  • [ ] 能夠使用轉換流讀取指定編碼的文字檔案
  • [ ] 能夠使用轉換流寫入指定編碼的文字檔案
  • [ ] 能夠說出列印流的特點
  • [ ] 能夠使用序列化流寫出物件到檔案
  • [ ] 能夠使用反序列化流讀取檔案到程式中

第一章 緩衝流

昨天學習了基本的一些流,作為IO流的入門,今天我們要見識一些更強大的流。比如能夠高效讀寫的緩衝流,能夠轉換編碼的轉換流,能夠持久化儲存物件的序列化流等等。這些功能更為強大的流,都是在基本的流物件基礎之上建立而來的,就像穿上鎧甲的武士一樣,相當於是對基本流物件的一種增強。

1.1 概述

緩衝流,也叫高效流,是對4個基本的FileXxx 流的增強,所以也是4個流,按照資料型別分類:

  • 位元組緩衝流BufferedInputStreamBufferedOutputStream
  • 字元緩衝流BufferedReaderBufferedWriter

緩衝流的基本原理,是在建立流物件時,會建立一個內建的預設大小的緩衝區陣列,通過緩衝區讀寫,減少系統IO次數,從而提高讀寫的效率。

1.2 位元組緩衝流

構造方法

  • public BufferedInputStream(InputStream in) :建立一個 新的緩衝輸入流。
  • public BufferedOutputStream(OutputStream out)
    : 建立一個新的緩衝輸出流。

構造舉例,程式碼如下:

// 建立位元組緩衝輸入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
// 建立位元組緩衝輸出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));

效率測試

查詢API,緩衝流讀寫方法與基本的流是一致的,我們通過複製大檔案(375MB),測試它的效率。

  1. 基本流,程式碼如下:
public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // 記錄開始時間
      	long start = System.currentTimeMillis();
		// 建立流物件
        try (
        	FileInputStream fis = new FileInputStream("jdk9.exe");
        	FileOutputStream fos = new FileOutputStream("copy.exe")
        ){
        	// 讀寫資料
            int b;
            while ((b = fis.read()) != -1) {
                fos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// 記錄結束時間
        long end = System.currentTimeMillis();
        System.out.println("普通流複製時間:"+(end - start)+" 毫秒");
    }
}

十幾分鍾過去了...
  1. 緩衝流,程式碼如下:
public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // 記錄開始時間
      	long start = System.currentTimeMillis();
		// 建立流物件
        try (
        	BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
	     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
        ){
        // 讀寫資料
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// 記錄結束時間
        long end = System.currentTimeMillis();
        System.out.println("緩衝流複製時間:"+(end - start)+" 毫秒");
    }
}

緩衝流複製時間:8016 毫秒

如何更快呢?

使用陣列的方式,程式碼如下:

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
      	// 記錄開始時間
        long start = System.currentTimeMillis();
		// 建立流物件
        try (
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
		 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
        ){
          	// 讀寫資料
            int len;
            byte[] bytes = new byte[8*1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0 , len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// 記錄結束時間
        long end = System.currentTimeMillis();
        System.out.println("緩衝流使用陣列複製時間:"+(end - start)+" 毫秒");
    }
}
緩衝流使用陣列複製時間:666 毫秒

1.3 字元緩衝流

構造方法

  • public BufferedReader(Reader in) :建立一個 新的緩衝輸入流。
  • public BufferedWriter(Writer out): 建立一個新的緩衝輸出流。

構造舉例,程式碼如下:

// 建立字元緩衝輸入流
BufferedReader br = new BufferedReader(new FileReader("br.txt"));
// 建立字元緩衝輸出流
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

特有方法

字元緩衝流的基本方法與普通字元流呼叫方式一致,不再闡述,我們來看它們具備的特有方法。

  • BufferedReader:public String readLine(): 讀一行文字。
  • BufferedWriter:public void newLine(): 寫一行行分隔符,由系統屬性定義符號。

readLine方法演示,程式碼如下:

public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
      	 // 建立流物件
        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
		// 定義字串,儲存讀取的一行文字
        String line  = null;
      	// 迴圈讀取,讀取到最後返回null
        while ((line = br.readLine())!=null) {
            System.out.print(line);
            System.out.println("------");
        }
		// 釋放資源
        br.close();
    }
}

newLine方法演示,程式碼如下:

public class BufferedWriterDemo throws IOException {
  public static void main(String[] args) throws IOException  {
    	// 建立流物件
  	BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
    	// 寫出資料
      bw.write("黑馬");
    	// 寫出換行
      bw.newLine();
      bw.write("程式");
      bw.newLine();
      bw.write("員");
      bw.newLine();
  	// 釋放資源
      bw.close();
  }
}
輸出效果:
黑馬
程式
員

1.4 練習:文字排序

請將文字資訊恢復順序。

3.侍中、侍郎郭攸之、費禕、董允等,此皆良實,志慮忠純,是以先帝簡拔以遺陛下。愚以為宮中之事,事無大小,悉以諮之,然後施行,必得裨補闕漏,有所廣益。
8.願陛下託臣以討賊興復之效,不效,則治臣之罪,以告先帝之靈。若無興德之言,則責攸之、禕、允等之慢,以彰其咎;陛下亦宜自謀,以諮諏善道,察納雅言,深追先帝遺詔,臣不勝受恩感激。
4.將軍向寵,性行淑均,曉暢軍事,試用之於昔日,先帝稱之曰能,是以眾議舉寵為督。愚以為營中之事,悉以諮之,必能使行陣和睦,優劣得所。
2.宮中府中,俱為一體,陟罰臧否,不宜異同。若有作奸犯科及為忠善者,宜付有司論其刑賞,以昭陛下平明之理,不宜偏私,使內外異法也。
1.先帝創業未半而中道崩殂,今天下三分,益州疲弊,此誠危急存亡之秋也。然侍衛之臣不懈於內,忠志之士忘身於外者,蓋追先帝之殊遇,欲報之於陛下也。誠宜開張聖聽,以光先帝遺德,恢弘志士之氣,不宜妄自菲薄,引喻失義,以塞忠諫之路也。
9.今當遠離,臨表涕零,不知所言。
6.臣本布衣,躬耕於南陽,苟全性命於亂世,不求聞達於諸侯。先帝不以臣卑鄙,猥自枉屈,三顧臣於草廬之中,諮臣以當世之事,由是感激,遂許先帝以驅馳。後值傾覆,受任於敗軍之際,奉命於危難之間,爾來二十有一年矣。
7.先帝知臣謹慎,故臨崩寄臣以大事也。受命以來,夙夜憂嘆,恐付託不效,以傷先帝之明,故五月渡瀘,深入不毛。今南方已定,兵甲已足,當獎率三軍,北定中原,庶竭駑鈍,攘除奸凶,興復漢室,還於舊都。此臣所以報先帝而忠陛下之職分也。至於斟酌損益,進盡忠言,則攸之、禕、允之任也。
5.親賢臣,遠小人,此先漢所以興隆也;親小人,遠賢臣,此後漢所以傾頹也。先帝在時,每與臣論此事,未嘗不嘆息痛恨於桓、靈也。侍中、尚書、長史、參軍,此悉貞良死節之臣,願陛下親之信之,則漢室之隆,可計日而待也。

案例分析

  1. 逐行讀取文字資訊。
  2. 解析文字資訊到集合中。
  3. 遍歷集合,按順序,寫出文字資訊。

案例實現

public class BufferedTest {    public static void main(String[] args) throws IOException {        // 建立map集合,儲存文字資料,鍵為序號,值為文字        HashMap<String, String> lineMap = new HashMap<>();        // 建立流物件        BufferedReader br = new BufferedReader(new FileReader("in.txt"));        BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));        // 讀取資料        String line  = null;        while ((line = br.readLine())!=null) {            // 解析文字            String[] split = line.split("\\.");            // 儲存到集合            lineMap.put(split[0],split[1]);        }        // 釋放資源        br.close();        // 遍歷map集合        for (int i = 1; i <= lineMap.size(); i++) {            String key = String.valueOf(i);            // 獲取map中文字            String value = lineMap.get(key);          	// 寫出拼接文字            bw.write(key+"."+value);          	// 寫出換行            bw.newLine();        }		// 釋放資源        bw.close();    }}

第二章 轉換流

2.1 字元編碼和字符集

字元編碼

計算機中儲存的資訊都是用二進位制數表示的,而我們在螢幕上看到的數字、英文、標點符號、漢字等字元是二進位制數轉換之後的結果。按照某種規則,將字元儲存到計算機中,稱為編碼 。反之,將儲存在計算機中的二進位制數按照某種規則解析顯示出來,稱為解碼 。比如說,按照A規則儲存,同樣按照A規則解析,那麼就能顯示正確的文字符號。反之,按照A規則儲存,再按照B規則解析,就會導致亂碼現象。

編碼:字元(能看懂的)--位元組(看不懂的)

解碼:位元組(看不懂的)-->字元(能看懂的)

  • 字元編碼Character Encoding : 就是一套自然語言的字元與二進位制數之間的對應規則。

    編碼表:生活中文字和計算機中二進位制的對應規則

字符集

  • 字符集 Charset:也叫編碼表。是一個系統支援的所有字元的集合,包括各國家文字、標點符號、圖形符號、數字等。

計算機要準確的儲存和識別各種字符集符號,需要進行字元編碼,一套字符集必然至少有一套字元編碼。常見字符集有ASCII字符集、GBK字符集、Unicode字符集等。

可見,當指定了編碼,它所對應的字符集自然就指定了,所以編碼才是我們最終要關心的。

  • ASCII字符集
    • ASCII(American Standard Code for Information Interchange,美國資訊交換標準程式碼)是基於拉丁字母的一套電腦編碼系統,用於顯示現代英語,主要包括控制字元(回車鍵、退格、換行鍵等)和可顯示字元(英文大小寫字元、阿拉伯數字和西文符號)。
    • 基本的ASCII字符集,使用7位(bits)表示一個字元,共128字元。ASCII的擴充套件字符集使用8位(bits)表示一個字元,共256字元,方便支援歐洲常用字元。
  • ISO-8859-1字符集
    • 拉丁碼錶,別名Latin-1,用於顯示歐洲使用的語言,包括荷蘭、丹麥、德語、義大利語、西班牙語等。
    • ISO-8859-1使用單位元組編碼,相容ASCII編碼。
  • GBxxx字符集
    • GB就是國標的意思,是為了顯示中文而設計的一套字符集。
    • GB2312:簡體中文碼錶。一個小於127的字元的意義與原來相同。但兩個大於127的字元連在一起時,就表示一個漢字,這樣大約可以組合了包含7000多個簡體漢字,此外數學符號、羅馬希臘的字母、日文的假名們都編進去了,連在ASCII裡本來就有的數字、標點、字母都統統重新編了兩個位元組長的編碼,這就是常說的"全形"字元,而原來在127號以下的那些就叫"半形"字元了。
    • GBK:最常用的中文碼錶。是在GB2312標準基礎上的擴充套件規範,使用了雙位元組編碼方案,共收錄了21003個漢字,完全相容GB2312標準,同時支援繁體漢字以及日韓漢字等。
    • GB18030:最新的中文碼錶。收錄漢字70244個,採用多位元組編碼,每個字可以由1個、2個或4個位元組組成。支援中國國內少數民族的文字,同時支援繁體漢字以及日韓漢字等。
  • Unicode字符集
    • Unicode編碼系統為表達任意語言的任意字元而設計,是業界的一種標準,也稱為統一碼、標準萬國碼。
    • 它最多使用4個位元組的數字來表達每個字母、符號,或者文字。有三種編碼方案,UTF-8、UTF-16和UTF-32。最為常用的UTF-8編碼。
    • UTF-8編碼,可以用來表示Unicode標準中任何字元,它是電子郵件、網頁及其他儲存或傳送文字的應用中,優先採用的編碼。網際網路工程工作小組(IETF)要求所有網際網路協議都必須支援UTF-8編碼。所以,我們開發Web應用,也要使用UTF-8編碼。它使用一至四個位元組為每個字元編碼,編碼規則:
      1. 128個US-ASCII字元,只需一個位元組編碼。
      2. 拉丁文等字元,需要二個位元組編碼。
      3. 大部分常用字(含中文),使用三個位元組編碼。
      4. 其他極少使用的Unicode輔助字元,使用四位元組編碼。

2.2 編碼引出的問題

在IDEA中,使用FileReader 讀取專案中的文字檔案。由於IDEA的設定,都是預設的UTF-8編碼,所以沒有任何問題。但是,當讀取Windows系統中建立的文字檔案時,由於Windows系統的預設是GBK編碼,就會出現亂碼。

public class ReaderDemo {    public static void main(String[] args) throws IOException {        FileReader fileReader = new FileReader("E:\\File_GBK.txt");        int read;        while ((read = fileReader.read()) != -1) {            System.out.print((char)read);        }        fileReader.close();    }}輸出結果:���

那麼如何讀取GBK編碼的檔案呢?

2.3 InputStreamReader類

轉換流java.io.InputStreamReader,是Reader的子類,是從位元組流到字元流的橋樑。它讀取位元組,並使用指定的字符集將其解碼為字元。它的字符集可以由名稱指定,也可以接受平臺的預設字符集。

構造方法

  • InputStreamReader(InputStream in): 建立一個使用預設字符集的字元流。
  • InputStreamReader(InputStream in, String charsetName): 建立一個指定字符集的字元流。

構造舉例,程式碼如下:

InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");

指定編碼讀取

public class ReaderDemo2 {    public static void main(String[] args) throws IOException {      	// 定義檔案路徑,檔案為gbk編碼        String FileName = "E:\\file_gbk.txt";      	// 建立流物件,預設UTF8編碼        InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));      	// 建立流物件,指定GBK編碼        InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK");		// 定義變數,儲存字元        int read;      	// 使用預設編碼字元流讀取,亂碼        while ((read = isr.read()) != -1) {            System.out.print((char)read); // ��Һ�        }        isr.close();            	// 使用指定編碼字元流讀取,正常解析        while ((read = isr2.read()) != -1) {            System.out.print((char)read);// 大家好        }        isr2.close();    }}

2.4 OutputStreamWriter類

轉換流java.io.OutputStreamWriter ,是Writer的子類,是從字元流到位元組流的橋樑。使用指定的字符集將字元編碼為位元組。它的字符集可以由名稱指定,也可以接受平臺的預設字符集。

構造方法

  • OutputStreamWriter(OutputStream in): 建立一個使用預設字符集的字元流。
  • OutputStreamWriter(OutputStream in, String charsetName): 建立一個指定字符集的字元流。

構造舉例,程式碼如下:

OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");

指定編碼寫出

public class OutputDemo {    public static void main(String[] args) throws IOException {      	// 定義檔案路徑        String FileName = "E:\\out.txt";      	// 建立流物件,預設UTF8編碼        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));        // 寫出資料      	osw.write("你好"); // 儲存為6個位元組        osw.close();      			// 定義檔案路徑		String FileName2 = "E:\\out2.txt";     	// 建立流物件,指定GBK編碼        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");        // 寫出資料      	osw2.write("你好");// 儲存為4個位元組        osw2.close();    }}

轉換流理解圖解

轉換流是位元組與字元間的橋樑!

2.5 練習:轉換檔案編碼

將GBK編碼的文字檔案,轉換為UTF-8編碼的文字檔案。

案例分析

  1. 指定GBK編碼的轉換流,讀取文字檔案。
  2. 使用UTF-8編碼的轉換流,寫出文字檔案。

案例實現

public class TransDemo {   public static void main(String[] args) {          	// 1.定義檔案路徑     	String srcFile = "file_gbk.txt";        String destFile = "file_utf8.txt";		// 2.建立流物件    	// 2.1 轉換輸入流,指定GBK編碼        InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile) , "GBK");    	// 2.2 轉換輸出流,預設utf8編碼        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile));		// 3.讀寫資料    	// 3.1 定義陣列        char[] cbuf = new char[1024];    	// 3.2 定義長度        int len;    	// 3.3 迴圈讀取        while ((len = isr.read(cbuf))!=-1) {            // 迴圈寫出          	osw.write(cbuf,0,len);        }    	// 4.釋放資源        osw.close();        isr.close();  	}}

第三章 序列化

3.1 概述

Java 提供了一種物件序列化的機制。用一個位元組序列可以表示一個物件,該位元組序列包含該物件的資料物件的型別物件中儲存的屬性等資訊。位元組序列寫出到檔案之後,相當於檔案中持久儲存了一個物件的資訊。

反之,該位元組序列還可以從檔案中讀取回來,重構物件,對它進行反序列化物件的資料物件的型別物件中儲存的資料資訊,都可以用來在記憶體中建立物件。看圖理解序列化:

3.2 ObjectOutputStream類

java.io.ObjectOutputStream 類,將Java物件的原始資料型別寫出到檔案,實現物件的持久儲存。

構造方法

  • public ObjectOutputStream(OutputStream out) : 建立一個指定OutputStream的ObjectOutputStream。

構造舉例,程式碼如下:

FileOutputStream fileOut = new FileOutputStream("employee.txt");ObjectOutputStream out = new ObjectOutputStream(fileOut);

序列化操作

  1. 一個物件要想序列化,必須滿足兩個條件:
  • 該類必須實現java.io.Serializable 介面,Serializable 是一個標記介面,不實現此介面的類將不會使任何狀態序列化或反序列化,會丟擲NotSerializableException
  • 該類的所有屬性必須是可序列化的。如果有一個屬性不需要可序列化的,則該屬性必須註明是瞬態的,使用transient 關鍵字修飾。
public class Employee implements java.io.Serializable {    public String name;    public String address;    public transient int age; // transient瞬態修飾成員,不會被序列化    public void addressCheck() {      	System.out.println("Address  check : " + name + " -- " + address);    }}

2.寫出物件方法

  • public final void writeObject (Object obj) : 將指定的物件寫出。
public class SerializeDemo{   	public static void main(String [] args)   {    	Employee e = new Employee();    	e.name = "zhangsan";    	e.address = "beiqinglu";    	e.age = 20;     	try {      		// 建立序列化流物件          ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"));        	// 寫出物件        	out.writeObject(e);        	// 釋放資源        	out.close();        	fileOut.close();        	System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年齡沒有被序列化。        } catch(IOException i)   {            i.printStackTrace();        }   	}}輸出結果:Serialized data is saved

3.3 ObjectInputStream類

ObjectInputStream反序列化流,將之前使用ObjectOutputStream序列化的原始資料恢復為物件。

構造方法

  • public ObjectInputStream(InputStream in) : 建立一個指定InputStream的ObjectInputStream。

反序列化操作1

如果能找到一個物件的class檔案,我們可以進行反序列化操作,呼叫ObjectInputStream讀取物件的方法:

  • public final Object readObject () : 讀取一個物件。
public class DeserializeDemo {   public static void main(String [] args)   {        Employee e = null;        try {		             // 建立反序列化流             FileInputStream fileIn = new FileInputStream("employee.txt");             ObjectInputStream in = new ObjectInputStream(fileIn);             // 讀取一個物件             e = (Employee) in.readObject();             // 釋放資源             in.close();             fileIn.close();        }catch(IOException i) {             // 捕獲其他異常             i.printStackTrace();             return;        }catch(ClassNotFoundException c)  {        	// 捕獲類找不到異常             System.out.println("Employee class not found");             c.printStackTrace();             return;        }        // 無異常,直接列印輸出        System.out.println("Name: " + e.name);	// zhangsan        System.out.println("Address: " + e.address); // beiqinglu        System.out.println("age: " + e.age); // 0    }}

對於JVM可以反序列化物件,它必須是能夠找到class檔案的類。如果找不到該類的class檔案,則丟擲一個 ClassNotFoundException 異常。

反序列化操作2

另外,當JVM反序列化物件時,能找到class檔案,但是class檔案在序列化物件之後發生了修改,那麼反序列化操作也會失敗,丟擲一個InvalidClassException異常。發生這個異常的原因如下:

  • 該類的序列版本號與從流中讀取的類描述符的版本號不匹配
  • 該類包含未知資料型別
  • 該類沒有可訪問的無引數構造方法

Serializable 介面給需要序列化的類,提供了一個序列版本號。serialVersionUID 該版本號的目的在於驗證序列化的物件和對應類是否版本匹配。

public class Employee implements java.io.Serializable {     // 加入序列版本號     private static final long serialVersionUID = 1L;     public String name;     public String address;     // 新增新的屬性 ,重新編譯, 可以反序列化,該屬性賦為預設值.     public int eid;      public void addressCheck() {         System.out.println("Address  check : " + name + " -- " + address);     }}

3.4 練習:序列化集合

  1. 將存有多個自定義物件的集合序列化操作,儲存到list.txt檔案中。
  2. 反序列化list.txt ,並遍歷集合,列印物件資訊。

案例分析

  1. 把若干學生物件 ,儲存到集合中。
  2. 把集合序列化。
  3. 反序列化讀取時,只需要讀取一次,轉換為集合型別。
  4. 遍歷集合,可以列印所有的學生資訊

案例實現

public class SerTest {	public static void main(String[] args) throws Exception {		// 建立 學生物件		Student student = new Student("老王", "laow");		Student student2 = new Student("老張", "laoz");		Student student3 = new Student("老李", "laol");		ArrayList<Student> arrayList = new ArrayList<>();		arrayList.add(student);		arrayList.add(student2);		arrayList.add(student3);		// 序列化操作		// serializ(arrayList);				// 反序列化  		ObjectInputStream ois  = new ObjectInputStream(new FileInputStream("list.txt"));		// 讀取物件,強轉為ArrayList型別		ArrayList<Student> list  = (ArrayList<Student>)ois.readObject();		      	for (int i = 0; i < list.size(); i++ ){          	Student s = list.get(i);        	System.out.println(s.getName()+"--"+ s.getPwd());      	}	}	private static void serializ(ArrayList<Student> arrayList) throws Exception {		// 建立 序列化流 		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));		// 寫出物件		oos.writeObject(arrayList);		// 釋放資源		oos.close();	}}

第四章 列印流

4.1 概述

平時我們在控制檯列印輸出,是呼叫print方法和println方法完成的,這兩個方法都來自於java.io.PrintStream類,該類能夠方便地列印各種資料型別的值,是一種便捷的輸出方式。

4.2 PrintStream類

構造方法

  • public PrintStream(String fileName) : 使用指定的檔名建立一個新的列印流。

構造舉例,程式碼如下:

PrintStream ps = new PrintStream("ps.txt");

改變列印流向

System.out就是PrintStream型別的,只不過它的流向是系統規定的,列印在控制檯上。不過,既然是流物件,我們就可以玩一個"小把戲",改變它的流向。

public class PrintDemo {    public static void main(String[] args) throws IOException {		// 呼叫系統的列印流,控制檯直接輸出97        System.out.println(97);      		// 建立列印流,指定檔案的名稱        PrintStream ps = new PrintStream("ps.txt");      	      	// 設定系統的列印流流向,輸出到ps.txt        System.setOut(ps);      	// 呼叫系統的列印流,ps.txt中輸出97        System.out.println(97);    }}

來源:黑馬Java,侵刪

慢慢來慢慢來