昨天覆習了基本的一些流,做爲IO流的入門,今天咱們要見識一些更強大的流。好比可以高效讀寫的緩衝流,可以轉換編碼的轉換流,可以持久化存儲對象的序列化流等等。這些功能更爲強大的流,都是在基本的流對象基礎之上建立而來的,至關因而對基本流對象的一種加強。java
緩衝流,也叫高效流,是對4個基本的FileXxx
流的加強,因此也是4個流,按照數據類型分類:數組
BufferedInputStream
,BufferedOutputStream
BufferedReader
,BufferedWriter
緩衝流的基本原理,是在建立流對象時,會建立一個內置的默認大小的緩衝區數組,經過緩衝區讀寫,減小系統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),測試它的效率。編碼
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)+" 毫秒"); } } 十幾分鍾過去了...
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 毫秒
如何更快呢?設計
使用數組的方式,代碼以下:code
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)
: 建立一個新的緩衝輸出流。構造舉例,代碼以下:orm
// 建立字符緩衝輸入流 BufferedReader br = new BufferedReader(new FileReader("br.txt")); // 建立字符緩衝輸出流 BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
字符緩衝流的基本方法與普通字符流調用方式一致,再也不闡述,咱們來看它們具有的特有方法。對象
public String readLine()
: 讀一行文字。public void newLine()
: 寫一行行分隔符,由系統屬性定義符號。readLine
方法演示,代碼以下:blog
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(); } } 輸出效果: 黑馬 程序 員
請將文本信息恢復順序。
3.侍中、侍郎郭攸之、費禕、董允等,此皆良實,志慮忠純,是以先帝簡拔以遺陛下。愚覺得宮中之事,事無大小,悉以諮之,而後施行,必得裨補闕漏,有所廣益。 8.願陛下託臣以討賊興復之效,不效,則治臣之罪,以告先帝之靈。若無興德之言,則責攸之、禕、允等之慢,以彰其咎;陛下亦宜自謀,以諮諏善道,察納雅言,深追先帝遺詔,臣不勝受恩感激。 4.將軍向寵,性行淑均,曉暢軍事,試用之於昔日,先帝稱之曰能,是以衆議舉寵爲督。愚覺得營中之事,悉以諮之,必能使行陣和氣,優劣得所。 2.宮中府中,俱爲一體,陟罰臧否,不宜異同。如有做奸犯科及爲忠善者,宜付有司論其刑賞,以昭陛下平明之理,不宜偏私,使內外異法也。 1.先帝創業未半而中道崩殂,今天下三分,益州疲弊,此誠危急存亡之秋也。然侍衛之臣不懈於內,忠志之士忘身於外者,蓋追先帝之殊遇,欲報之於陛下也。誠宜開張聖聽,以光先帝遺德,恢弘志士之氣,不宜妄自菲薄,引喻失義,以塞忠諫之路也。 9.今當遠離,臨表涕零,不知所言。 6.臣本布衣,躬耕於南陽,苟全性命於亂世,不求聞達於諸侯。先帝不以臣卑鄙,猥自枉屈,三顧臣於草廬之中,諮臣以當世之事,由是感激,遂許先帝以驅馳。後值傾覆,受任於敗軍之際,奉命於危難之間,爾來二十有一年矣。 7.先帝知臣謹慎,故臨崩寄臣以大事也。受命以來,夙夜憂嘆,恐付託不效,以傷先帝之明,故五月渡瀘,深刻不毛。今南方已定,兵甲已足,當獎率三軍,北定中原,庶竭駑鈍,攘除奸兇,興復漢室,還於舊都。此臣因此報先帝而忠陛下之職分也。至於斟酌損益,進盡忠言,則攸之、禕、允之任也。 5.親賢臣,遠小人,此先漢因此興隆也;親小人,遠賢臣,此後漢因此傾頹也。先帝在時,每與臣論此事,何嘗不嘆息痛恨於桓、靈也。侍中、尚書、長史、參軍,此悉貞良死節之臣,願陛下親之信之,則漢室之隆,可計日而待也。
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(); } }
計算機中儲存的信息都是用二進制數表示的,而咱們在屏幕上看到的數字、英文、標點符號、漢字等字符是二進制數轉換以後的結果。按照某種規則,將字符存儲到計算機中,稱爲編碼 。反之,將存儲在計算機中的二進制數按照某種規則解析顯示出來,稱爲解碼 。好比說,按照A規則存儲,一樣按照A規則解析,那麼就能顯示正確的文本符號。反之,按照A規則存儲,再按照B規則解析,就會致使亂碼現象。
編碼:字符(能看懂的)--字節(看不懂的)
解碼:字節(看不懂的)-->字符(能看懂的)
字符編碼Character Encoding
: 就是一套天然語言的字符與二進制數之間的對應規則。
編碼表:生活中文字和計算機中二進制的對應規則
Charset
:也叫編碼表。是一個系統支持的全部字符的集合,包括各國家文字、標點符號、圖形符號、數字等。計算機要準確的存儲和識別各類字符集符號,須要進行字符編碼,一套字符集必然至少有一套字符編碼。常見字符集有ASCII字符集、GBK字符集、Unicode字符集等。
可見,當指定了編碼,它所對應的字符集天然就指定了,因此編碼纔是咱們最終要關心的。
在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編碼的文件呢?
轉換流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(); } }
轉換流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編碼的文本文件。
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(); } }
Java 提供了一種對象序列化的機制。用一個字節序列能夠表示一個對象,該字節序列包含該對象的數據
、對象的類型
和對象中存儲的屬性
等信息。字節序列寫出到文件以後,至關於文件中持久保存了一個對象的信息。
反之,該字節序列還能夠從文件中讀取回來,重構對象,對它進行反序列化。對象的數據
、對象的類型
和對象中存儲的數據
信息,均可以用來在內存中建立對象。看圖理解序列化: !
java.io.ObjectOutputStream
類,將Java對象的原始數據類型寫出到文件,實現對象的持久存儲。
public ObjectOutputStream(OutputStream out)
: 建立一個指定OutputStream的ObjectOutputStream。構造舉例,代碼以下:
FileOutputStream fileOut = new FileOutputStream("employee.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut);
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反序列化流,將以前使用ObjectOutputStream序列化的原始數據恢復爲對象。
public ObjectInputStream(InputStream in)
: 建立一個指定InputStream的ObjectInputStream。若是能找到一個對象的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
異常。
另外,當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); } }
list.txt
文件中。list.txt
,並遍歷集合,打印對象信息。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(); } }
平時咱們在控制檯打印輸出,是調用print
方法和println
方法完成的,這兩個方法都來自於java.io.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); } }