1. 程式人生 > 實用技巧 >mysql觸發器trigger 例項詳解

mysql觸發器trigger 例項詳解

IO概述

我們把這種資料的傳輸,可以看做是一種資料的流動,按照流動的方向,以記憶體為基準,分為輸入input和輸出
output,即流向記憶體是輸入流,流出記憶體的輸出流。

Java中I/O操作主要是指使用java. io包下的內容,進行輸入,輸出操作。輸入也叫做讀取資料,輸出也叫做作寫
出資料。

IO的分類

根據資料的流向分為:輸入流和輸出流。

  • 輸入流:把資料從其他裝置上讀取到記憶體中的流。
  • 輸出流:把資料從記憶體中寫出到其他裝置上的流。

根據資料的型別分為:位元組流和字元流。

  • 位元組流:以位元組為單位,讀寫資料的流。
  • 字元流: 以字元為單位,讀寫資料的流。

頂級父類們

輸入流 輸出流
位元組流 位元組輸入流
InputStream
位元組輸出流
OutputStream
字元流 字元輸入流
Reader
字元輸出流
Writer

一切皆為位元組

一切檔案資料(文字、 圖片、視訊等)在儲存時,都是以二進位制數字的形式儲存,都是一個一個的位元組 ,那麼傳輸時一
樣如此。所以,位元組流可以傳輸任意檔案資料。在操作流的時候,我們要時刻明確,無論使用什麼樣的流物件,底
層傳輸的始終為二進位制資料。

位元組輸出流【OutputStream】

java.io.OutputStream 抽象類是表示位元組輸出流的所有類的超類,將指定的位元組資訊寫出到目的地。它定義了位元組輸出流的基本共性功能方法。

  • public void close() :關閉此輸出流並釋放與此流相關聯的任何系統資源。
  • public void flush() :重新整理此輸出流並強制任何緩衝的輸出位元組被寫出。
  • public void write(byte[] b):將 b.length位元組從指定的位元組陣列寫入此輸出流。
  • public void write(byte[] b, int off, int len) :從指定的位元組陣列寫入 len位元組,從偏移量 off開始輸出到此輸出流。
  • public abstract void write(int b) :將指定的位元組輸出流。

小貼士:

close方法,當完成流的操作時,必須呼叫此方法,釋放系統資源。

FileOutputStream類

OutputStream有很多子類,我們從最簡單的一個子類開始。

java.io.FileOutputStream 類是檔案輸出流,用於將資料寫出到檔案。

構造方法

  • public FileOutputStream(File file):建立檔案輸出流以寫入由指定的 File物件表示的檔案。
  • public FileOutputStream(String name): 建立檔案輸出流以指定的名稱寫入檔案。

當你建立一個流物件時,必須傳入一個檔案路徑。該路徑下,如果沒有這個檔案,會建立該檔案。如果有這個檔案,會清空這個檔案的資料。

  • 構造舉例,程式碼如下:
public class FileOutputStreamConstructor throws IOException {
    public static void main(String[] args) {
   	 	// 使用File物件建立流物件
        File file = new File("a.txt");
        FileOutputStream fos = new FileOutputStream(file);
      
        // 使用檔名稱建立流物件
        FileOutputStream fos = new FileOutputStream("b.txt");
    }
}

寫出位元組資料

  1. 寫出位元組write(int b) 方法,每次可以寫出一個位元組資料,程式碼使用演示:
public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileOutputStream fos = new FileOutputStream("fos.txt");     
      	// 寫出資料
      	fos.write(97); // 寫出第1個位元組
      	fos.write(98); // 寫出第2個位元組
      	fos.write(99); // 寫出第3個位元組
      	// 關閉資源
        fos.close();
    }
}
輸出結果:
abc

小貼士:

  1. 雖然引數為int型別四個位元組,但是隻會保留一個位元組的資訊寫出。
  2. 流操作完畢後,必須釋放系統資源,呼叫close方法,千萬記得。
  1. 寫出位元組陣列write(byte[] b),每次可以寫出陣列中的資料,程式碼使用演示:
public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileOutputStream fos = new FileOutputStream("fos.txt");     
      	// 字串轉換為位元組陣列
      	byte[] b = "hsz".getBytes();
      	// 寫出位元組陣列資料
      	fos.write(b);
      	// 關閉資源
        fos.close();
    }
}
輸出結果:
hsz
  1. 寫出指定長度位元組陣列write(byte[] b, int off, int len) ,每次寫出從off索引開始,len個位元組,程式碼使用演示:
public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileOutputStream fos = new FileOutputStream("fos.txt");     
      	// 字串轉換為位元組陣列
      	byte[] b = "abcde".getBytes();
		// 寫出從索引2開始,2個位元組。索引2是c,兩個位元組,也就是cd。
        fos.write(b,2,2);
      	// 關閉資源
        fos.close();
    }
}
輸出結果:
cd

資料追加續寫

經過以上的演示,每次程式執行,建立輸出流物件,都會清空目標檔案中的資料。如何保留目標檔案中資料,還能繼續新增新資料呢?

  • public FileOutputStream(File file, boolean append): 建立檔案輸出流以寫入由指定的 File物件表示的檔案。
  • public FileOutputStream(String name, boolean append): 建立檔案輸出流以指定的名稱寫入檔案。

這兩個構造方法,引數中都需要傳入一個boolean型別的值,true 表示追加資料,false 表示清空原有資料。這樣建立的輸出流物件,就可以指定是否追加續寫了,程式碼使用演示:

public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileOutputStream fos = new FileOutputStream("fos.txt",true);     
      	// 字串轉換為位元組陣列
      	byte[] b = "abcde".getBytes();
		// 寫出從索引2開始,2個位元組。索引2是c,兩個位元組,也就是cd。
        fos.write(b);
      	// 關閉資源
        fos.close();
    }
}
檔案操作前:cd
檔案操作後:cdabcde

寫出換行

Windows系統裡,換行符號是\r\n 。把

以指定是否追加續寫了,程式碼使用演示:

public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileOutputStream fos = new FileOutputStream("fos.txt");  
      	// 定義位元組陣列
      	byte[] words = {97,98,99,100,101};
      	// 遍歷陣列
        for (int i = 0; i < words.length; i++) {
          	// 寫出一個位元組
            fos.write(words[i]);
          	// 寫出一個換行, 換行符號轉成陣列寫出
            fos.write("\r\n".getBytes());
        }
      	// 關閉資源
        fos.close();
    }
}

輸出結果:
a
b
c
d
e
  • 回車符\r和換行符\n
    • 回車符:回到一行的開頭(return)。
    • 換行符:下一行(newline)。
  • 系統中的換行:
    • Windows系統裡,每行結尾是 回車+換行 ,即\r\n
    • Unix系統裡,每行結尾只有 換行 ,即\n
    • Mac系統裡,每行結尾是 回車 ,即\r。從 Mac OS X開始與Linux統一。

位元組輸入流【InputStream】

java.io.InputStream 抽象類是表示位元組輸入流的所有類的超類,可以讀取位元組資訊到記憶體中。它定義了位元組輸入流的基本共性功能方法。

  • public void close() :關閉此輸入流並釋放與此流相關聯的任何系統資源。
  • public abstract int read(): 從輸入流讀取資料的下一個位元組。
  • public int read(byte[] b): 從輸入流中讀取一些位元組數,並將它們儲存到位元組陣列 b中 。

小貼士:

close方法,當完成流的操作時,必須呼叫此方法,釋放系統資源。

FileInputStream類

java.io.FileInputStream 類是檔案輸入流,從檔案中讀取位元組。

構造方法

  • FileInputStream(File file): 通過開啟與實際檔案的連線來建立一個 FileInputStream ,該檔案由檔案系統中的 File物件 file命名。
  • FileInputStream(String name): 通過開啟與實際檔案的連線來建立一個 FileInputStream ,該檔案由檔案系統中的路徑名 name命名。

當你建立一個流物件時,必須傳入一個檔案路徑。該路徑下,如果沒有該檔案,會丟擲FileNotFoundException

  • 構造舉例,程式碼如下:

public class FileInputStreamConstructor throws IOException{
public static void main(String[] args) {
// 使用File物件建立流物件
File file = new File("a.txt");
FileInputStream fos = new FileInputStream(file);

    // 使用檔名稱建立流物件
    FileInputStream fos = new FileInputStream("b.txt");
}

}

讀取位元組資料

  1. 讀取位元組read方法,每次可以讀取一個位元組的資料,提升為int型別,讀取到檔案末尾,返回-1,程式碼使用演示:
public class FISRead {
    public static void main(String[] args) throws IOException{
      	// 使用檔名稱建立流物件
       	FileInputStream fis = new FileInputStream("read.txt");
      	// 讀取資料,返回一個位元組
        int read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
      	// 讀取到末尾,返回-1
       	read = fis.read();
        System.out.println( read);
		// 關閉資源
        fis.close();
    }
}
輸出結果:
a
b
c
d
e
-1

迴圈改進讀取方式,程式碼使用演示:

public class FISRead {
    public static void main(String[] args) throws IOException{
      	// 使用檔名稱建立流物件
       	FileInputStream fis = new FileInputStream("read.txt");
      	// 定義變數,儲存資料
        int b ;
        // 迴圈讀取
        while ((b = fis.read())!=-1) {
            System.out.println((char)b);
        }
		// 關閉資源
        fis.close();
    }
}
輸出結果:
a
b
c
d
e

小貼士:

  1. 雖然讀取了一個位元組,但是會自動提升為int型別。
  2. 流操作完畢後,必須釋放系統資源,呼叫close方法,千萬記得。
  1. 使用位元組陣列讀取read(byte[] b),每次讀取b的長度個位元組到陣列中,返回讀取到的有效位元組個數,讀取到末尾時,返回-1 ,程式碼使用演示:
public class FISRead {
    public static void main(String[] args) throws IOException{
      	// 使用檔名稱建立流物件.
       	FileInputStream fis = new FileInputStream("read.txt"); // 檔案中為abcde
      	// 定義變數,作為有效個數
        int len ;
        // 定義位元組陣列,作為裝位元組資料的容器   
        byte[] b = new byte[2];
        // 迴圈讀取
        while (( len= fis.read(b))!=-1) {
           	// 每次讀取後,把陣列變成字串列印
            System.out.println(new String(b));
        }
		// 關閉資源
        fis.close();
    }
}

輸出結果:
ab
cd
ed

錯誤資料d,是由於最後一次讀取時,只讀取一個位元組e,陣列中,上次讀取的資料沒有被完全替換,所以要通過len ,獲取有效的位元組,程式碼使用演示:

public class FISRead {
    public static void main(String[] args) throws IOException{
      	// 使用檔名稱建立流物件.
       	FileInputStream fis = new FileInputStream("read.txt"); // 檔案中為abcde
      	// 定義變數,作為有效個數
        int len ;
        // 定義位元組陣列,作為裝位元組資料的容器   
        byte[] b = new byte[2];
        // 迴圈讀取
        while (( len= fis.read(b))!=-1) {
           	// 每次讀取後,把陣列的有效位元組部分,變成字串列印
            System.out.println(new String(b,0,len));//  len 每次讀取的有效位元組個數
        }
		// 關閉資源
        fis.close();
    }
}

輸出結果:
ab
cd
e

小貼士:

使用陣列讀取,每次讀取多個位元組,減少了系統間的IO操作次數,從而提高了讀寫的效率,建議開發中使用。

複製檔案

案例實現

複製圖片檔案,程式碼使用演示:

public class Copy {
    public static void main(String[] args) throws IOException {
        // 1.建立流物件
        // 1.1 指定資料來源
        FileInputStream fis = new FileInputStream("D:\\test.jpg");
        // 1.2 指定目的地
        FileOutputStream fos = new FileOutputStream("test_copy.jpg");

        // 2.讀寫資料
        // 2.1 定義陣列
        byte[] b = new byte[1024];
        // 2.2 定義長度
        int len;
        // 2.3 迴圈讀取
        while ((len = fis.read(b))!=-1) {
            // 2.4 寫出資料
            fos.write(b, 0 , len);
        }

        // 3.關閉資源
        fos.close();
        fis.close();
    }
}

小貼士:

流的關閉原則:先開後關,後開先關。

字元輸入流【Reader】

java.io.Reader抽象類是表示用於讀取字元流的所有類的超類,可以讀取字元資訊到記憶體中。它定義了字元輸入流的基本共性功能方法。

  • public void close() :關閉此流並釋放與此流相關聯的任何系統資源。
  • public int read(): 從輸入流讀取一個字元。
  • public int read(char[] cbuf): 從輸入流中讀取一些字元,並將它們儲存到字元陣列 cbuf中 。

FileReader類

java.io.FileReader 類是讀取字元檔案的便利類。構造時使用系統預設的字元編碼和預設位元組緩衝區。

小貼士:

  1. 字元編碼:位元組與字元的對應規則。Windows系統的中文編碼預設是GBK編碼表。

    idea中UTF-8

  2. 位元組緩衝區:一個位元組陣列,用來臨時儲存位元組資料。

構造方法

  • FileReader(File file): 建立一個新的 FileReader ,給定要讀取的File物件。
  • FileReader(String fileName): 建立一個新的 FileReader ,給定要讀取的檔案的名稱。

當你建立一個流物件時,必須傳入一個檔案路徑。類似於FileInputStream 。

  • 構造舉例,程式碼如下:
public class FileReaderConstructor throws IOException{
    public static void main(String[] args) {
   	 	// 使用File物件建立流物件
        File file = new File("a.txt");
        FileReader fr = new FileReader(file);
      
        // 使用檔名稱建立流物件
        FileReader fr = new FileReader("b.txt");
    }
}

讀取字元資料

  1. 讀取字元read方法,每次可以讀取一個字元的資料,提升為int型別,讀取到檔案末尾,返回-1,迴圈讀取,程式碼使用演示:
public class FRRead {
    public static void main(String[] args) throws IOException {
      	// 使用檔名稱建立流物件
       	FileReader fr = new FileReader("read.txt");
      	// 定義變數,儲存資料
        int b ;
        // 迴圈讀取
        while ((b = fr.read())!=-1) {
            System.out.println((char)b);
        }
		// 關閉資源
        fr.close();
    }
}
輸出結果:
大
意
失
荊
州

小貼士:雖然讀取了一個字元,但是會自動提升為int型別。

  1. 使用字元陣列讀取read(char[] cbuf),每次讀取b的長度個字元到陣列中,返回讀取到的有效字元個數,讀取到末尾時,返回-1 ,程式碼使用演示:
public class FRRead {
    public static void main(String[] args) throws IOException {
      	// 使用檔名稱建立流物件
       	FileReader fr = new FileReader("read.txt");
      	// 定義變數,儲存有效字元個數
        int len ;
        // 定義字元陣列,作為裝字元資料的容器
         char[] cbuf = new char[2];
        // 迴圈讀取
        while ((len = fr.read(cbuf))!=-1) {
            System.out.println(new String(cbuf));
        }
		// 關閉資源
        fr.close();
    }
}
輸出結果:
大意
失荊
州荊

獲取有效的字元改進,程式碼使用演示:

public class FISRead {
    public static void main(String[] args) throws IOException {
      	// 使用檔名稱建立流物件
       	FileReader fr = new FileReader("read.txt");
      	// 定義變數,儲存有效字元個數
        int len ;
        // 定義字元陣列,作為裝字元資料的容器
        char[] cbuf = new char[2];
        // 迴圈讀取
        while ((len = fr.read(cbuf))!=-1) {
            System.out.println(new String(cbuf,0,len));
        }
    	// 關閉資源
        fr.close();
    }
}

輸出結果:
大意
失荊
州

字元輸出流【Writer】

java.io.Writer 抽象類是表示用於寫出字元流的所有類的超類,將指定的字元資訊寫出到目的地。它定義了位元組輸出流的基本共性功能方法。

  • void write(int c) 寫入單個字元。
  • void write(char[] cbuf) 寫入字元陣列。
  • abstract void write(char[] cbuf, int off, int len) 寫入字元陣列的某一部分,off陣列的開始索引,len寫的字元個數。
  • void write(String str) 寫入字串。
  • void write(String str, int off, int len) 寫入字串的某一部分,off字串的開始索引,len寫的字元個數。
  • void flush() 重新整理該流的緩衝。
  • void close() 關閉此流,但要先重新整理它。

FileWriter類

java.io.FileWriter 類是寫出字元到檔案的便利類。構造時使用系統預設的字元編碼和預設位元組緩衝區。

構造方法

  • FileWriter(File file): 建立一個新的 FileWriter,給定要讀取的File物件。
  • FileWriter(String fileName): 建立一個新的 FileWriter,給定要讀取的檔案的名稱。

當你建立一個流物件時,必須傳入一個檔案路徑,類似於FileOutputStream。

  • 構造舉例,程式碼如下:
public class FileWriterConstructor {
    public static void main(String[] args) throws IOException {
   	 	// 使用File物件建立流物件
        File file = new File("a.txt");
        FileWriter fw = new FileWriter(file);
      
        // 使用檔名稱建立流物件
        FileWriter fw = new FileWriter("b.txt");
    }
}

基本寫出資料

寫出字元write(int b) 方法,每次可以寫出一個字元資料,程式碼使用演示:

public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileWriter fw = new FileWriter("fw.txt");     
      	// 寫出資料
      	fw.write(97); // 寫出第1個字元
      	fw.write('b'); // 寫出第2個字元
      	fw.write('C'); // 寫出第3個字元
      	fw.write(30000); // 寫出第4個字元,中文編碼表中30000對應一個漢字。
      
      	/*
        【注意】關閉資源時,與FileOutputStream不同。
      	 如果不關閉,資料只是儲存到緩衝區,並未儲存到檔案。
        */
        // fw.close();
    }
}
輸出結果:
abC田

小貼士:

  1. 雖然引數為int型別四個位元組,但是隻會保留一個字元的資訊寫出。
  2. 未呼叫close方法,資料只是儲存到了緩衝區,並未寫出到檔案中。

關閉和重新整理

因為內建緩衝區的原因,如果不關閉輸出流,無法寫出字元到檔案中。但是關閉的流物件,是無法繼續寫出資料的。如果我們既想寫出資料,又想繼續使用流,就需要flush 方法了。

  • flush :重新整理緩衝區,流物件可以繼續使用。
  • close :先重新整理緩衝區,然後通知系統釋放資源。流物件不可以再被使用了。

程式碼使用演示:

public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileWriter fw = new FileWriter("fw.txt");
        // 寫出資料,通過flush
        fw.write('刷'); // 寫出第1個字元
        fw.flush();
        fw.write('新'); // 繼續寫出第2個字元,寫出成功
        fw.flush();
      
      	// 寫出資料,通過close
        fw.write('關'); // 寫出第1個字元
        fw.close();
        fw.write('閉'); // 繼續寫出第2個字元,【報錯】java.io.IOException: Stream closed
        fw.close();
    }
}

小貼士:即便是flush方法寫出了資料,操作的最後還是要呼叫close方法,釋放系統資源。

寫出其他資料

  1. 寫出字元陣列write(char[] cbuf)write(char[] cbuf, int off, int len) ,每次可以寫出字元陣列中的資料,用法類似FileOutputStream,程式碼使用演示:
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileWriter fw = new FileWriter("fw.txt");     
      	// 字串轉換為位元組陣列
      	char[] chars = "大意失荊州".toCharArray();
      
      	// 寫出字元陣列
      	fw.write(chars); // 黑馬程式設計師
        
		// 寫出從索引2開始,2個位元組。索引2是'程',兩個位元組,也就是'程式'。
        fw.write(b,2,2); // 程式
      
      	// 關閉資源
        fos.close();
    }
}
  1. 寫出字串write(String str)write(String str, int off, int len) ,每次可以寫出字串中的資料,更為方便,程式碼使用演示:
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件
        FileWriter fw = new FileWriter("fw.txt");     
      	// 字串
      	String msg = "大意失荊州";
      
      	// 寫出字元陣列
      	fw.write(msg); //大意失荊州
      
		// 寫出從索引2開始,2個位元組。索引2是'失',兩個位元組,也就是'失荊'。
        fw.write(msg,2,2);	// 失荊
      	
        // 關閉資源
        fos.close();
    }
}
  1. 續寫和換行:操作類似於FileOutputStream。
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用檔名稱建立流物件,可以續寫資料
        FileWriter fw = new FileWriter("fw.txt",true);     
      	// 寫出字串
        fw.write("大意");
      	// 寫出換行
      	fw.write("\r\n");
      	// 寫出字串
  		fw.write("失荊州");
      	// 關閉資源
        fw.close();
    }
}
輸出結果:
大意
失荊州

小貼士:字元流,只能操作文字檔案,不能操作圖片,視訊等非文字檔案。

當我們單純讀或者寫文字檔案時 使用字元流 其他情況使用位元組流

緩衝流

概述

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

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

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

位元組緩衝流

構造方法

  • 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 毫秒

字元緩衝流

構造方法

  • 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();
  }
}
輸出效果:
大意
失荊
州

轉換流

字元編碼和字符集

字元編碼

計算機中儲存的資訊都是用二進位制數表示的,而我們在螢幕上看到的數字、英文、標點符號、漢字等字元是二進位制數轉換之後的結果。按照某種規則,將字元儲存到計算機中,稱為編碼 。反之,將儲存在計算機中的二進位制數按照某種規則解析顯示出來,稱為解碼 。比如說,按照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輔助字元,使用四位元組編碼。

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();
    }
}

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();
    }
}

轉換流理解圖解

轉換檔案編碼

將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();
  	}
}

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

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);
     }
}

列印流

概述

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

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);
    }
}