摘要

之前一周学习了基础的IO流,现在学更牛逼的流!

比如能够高效读写的缓冲流,能够转换编码的转换流,能够持久化存储对象的序列化流等等。这些功能更为强大的流,都是在基本的流对象基础之上创建而来的,就像穿上铠甲的武士一样,相当于是对基本流对象的一种增强。

正文

第一章 缓冲流

1.1 概述

缓冲流,也叫高效流,是对4个基本的FileXxx 流的增强,所以也是4个流,按照数据类型分类:

  • 字节缓冲流BufferedInputStreamBufferedOutputStream
  • 字符缓冲流BufferedReaderBufferedWriter

缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。

理解原理:

缓冲流的原理.png

1.2 字节缓冲流

1.2.1 字节缓冲输出流

构造方法:

  • BufferedOutputStream(OutputStream out) 创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
  • BufferedOutputStream(OutputStream out, int size) 创建一个新的缓冲输出流,以将具有指定缓冲区大小的数据写入指定的底层输出流。

参数:

  • OutputStream out:字节输出流,可以传递FileOutputStream,缓冲流会给FileOutputStream增加一个缓冲区,提高FileOutputStream的写入效率
  • int size:指定缓冲流内部缓冲区的大小,不指定就是默认的大小

使用步骤:

  1. 创建一个FileOutputStream对象,构造方法中绑定要输出的目的地

  2. 创建BufferedOutputStream对象,构造方法中传递FileOutputStream对象,提高FileOutputStream的效率

  3. 使用BufferdOutputStream对象中的方法write,把数据写入到内部缓冲区中

  4. 使用BufferdOutputStream对象中的方法flush,把内部缓冲区中的数据刷新到文件中

  5. 释放资源(会调用flush,刷新数据),所以第四步可以省略

案例:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static void main(String[] args) {
		try(FileOutputStream fos=new FileOutputStream("C:\\users\\kitchen\\desktop\\abc\\abc.txt");
				BufferedOutputStream bos=new BufferedOutputStream(fos);) {
		bos.write("我把数据写入到内部缓冲区中".getBytes());
//		bos.flush();
//		bos.close();
		//上面这几步不用再写,因为在jdk1.7中,自动刷新flush关闭close()
	} catch (Exception e) {
		e.printStackTrace();
	}
		
}

1.2.2 字节缓冲输入流

构造方法:

  • BufferedInputStream(InputStream in) 创建一个 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。
  • BufferedInputStream(InputStream in, int size) 创建具有指定缓冲区大小的 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。

参数:

  • InputStream in:字节输入流,可以传递FileInputStream,缓冲流会给FileInputStream增加一个缓冲区,提高FileInputStream的读取效率
  • int size:指定缓冲流内部缓冲区的大小,不指定就是默认的大小

使用步骤:

  1. 创建FileInputStream对象,构造方法中绑定要读取的数据源
  2. 创建BufferedInputStream对象,构造方法中传入FileInputStream对象,提高FileInputStream对象的读取效率
  3. 使用BufferedInputStream对象中的read方法,将数据读取到内部缓冲区中
  4. 释放资源

案例:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static void main(String[] args) {
		try(FileInputStream fis=new FileInputStream("C:\\users\\kitchen\\desktop\\abc\\abc.txt");
				BufferedInputStream bis=new BufferedInputStream(fis);) {
			int len=0;
			byte[] b=new byte[1024];
			while((len=bis.read(b))!=-1) {
				System.out.println(new String(b,0,len));
			}
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		}
}

1.2.3 效率测试

查询API,缓冲流读写方法与基本的流是一致的,我们通过复制大文件(277MB),测试它的效率。

  1. 基本流,代码如下:
java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class Demo03Effectiveness {
	public static void main(String[] args) {
		//不使用字节缓冲流,277M文件复制11889毫秒
		long beginTime=System.currentTimeMillis();
		try(FileOutputStream fos=new FileOutputStream("C:\\Users\\kitchen\\Desktop\\abc\\copy.exe");
				FileInputStream fis=new FileInputStream("C:\\Users\\kitchen\\Desktop\\PhpStorm-2019.2.5.exe")) {
			byte[] b=new byte[1024];
			int len=0;
			while((len=fis.read(b))!=-1) {
				fos.write(b, 0, len);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("复制过程总共历时"+(System.currentTimeMillis()-beginTime)+"毫秒");
		}
    }
}
  1. 缓冲流,代码如下:
java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Demo03Effectiveness {
	public static void main(String[] args) {
		//使用字节缓冲流,277M文件复制1433毫秒
		try(BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("C:\\Users\\kitchen\\Desktop\\abc\\copy.exe"));
				BufferedInputStream bis=new BufferedInputStream(new FileInputStream("C:\\Users\\kitchen\\Desktop\\PhpStorm-2019.2.5.exe"))) {
			int len=0;
			byte[] b=new byte[1024];
			while((len=bis.read(b))!=-1) {
				bos.write(b, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			System.out.println("复制过程总共历时"+(System.currentTimeMillis()-beginTime)+"毫秒");
		}
    }
}

如何更快呢?

使用数组的方式,代码如下:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Demo03Effectiveness {
	public static void main(String[] args) {
		//使用字节缓冲流,277M文件复制480毫秒
		try(BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("C:\\Users\\kitchen\\Desktop\\abc\\copy.exe"));
				BufferedInputStream bis=new BufferedInputStream(new FileInputStream("C:\\Users\\kitchen\\Desktop\\PhpStorm-2019.2.5.exe"))) {
			int len=0;
			byte[] b=new byte[1024*100];
			while((len=bis.read(b))!=-1) {
				bos.write(b, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			System.out.println("复制过程总共历时"+(System.currentTimeMillis()-beginTime)+"毫秒");
		}
    }
}

1.3 字符缓冲流

1.3.1 字符缓冲输出流

构造方法:

  • BufferedWriter(Writer out) 创建一个使用默认大小输出缓冲区的缓冲字符输出流。
  • BufferedWriter(Writer out, int sz) 创建一个使用给定大小输出缓冲区的新缓冲字符输出流。

参数:

Writer out:字符输出流。我们可以传递FileWriter,缓冲流会给FileWriter增加一个缓冲区,以提高FileWriter的写入效率

int sz:指定缓冲区的大小,不写就是默认的大小。

特有的成员方法:

void newLine();写入一个行分割符。会根据不同的操作系统,获取不同的行分割符

换行符:不同的操作系统,换行符也不同

windows:\r\n

linux:/n

max:\r

使用步骤:

  1. 创建一个字符缓冲输出流对象,构造方法中传递字符输出流
  2. 调用字符缓冲输出流中的方法write,把数据写入到内存缓冲区中
  3. 调用字符缓冲输出流中的方法flush,把内存缓冲区中的数据刷新到文件中
  4. 释放资源

案例:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Demo04BufferedWriter {
	public static void main(String[] args) {
		try(BufferedWriter bw=new BufferedWriter(new FileWriter("src\\demo36\\abc.txt"))){
			for(int i=0;i<10;i++) {
				bw.write("我是你爸爸,嘎嘎嘎");
				bw.newLine();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}

1.3.2 字符缓冲输入流

构造方法

  • BufferedReader(Reader in) 创建一个使用默认大小输入缓冲区的缓冲字符输入流。
  • BufferedReader(Reader in, int sz) 创建一个使用指定大小输入缓冲区的缓冲字符输入流。

使用步骤:

  1. 创建字符缓冲输入流对象,构造方法中传递字符输入流

  2. 使用字符缓冲输入流对象中的方法read或者readLine,读取文本

  3. 释放资源

构造举例,代码如下:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Demo05BufferedReader {
	public static void main(String[] args) {
		try(BufferedReader br=new BufferedReader(new FileReader("src\\demo36\\abc.txt"));){
//			String line="";
//			while((line=br.readLine())!=null) {
//				System.out.println(line);
//			}
			
			int len=0;
			char[] b=new char[10];
			while((len=br.read(b))!=-1) {
				System.out.println(new String(b,0,len));
			}
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
}

1.3.3 两者的特有方法

字符缓冲流的基本方法与普通字符流调用方式一致,不再阐述,我们来看它们具备的特有方法。

  • BufferedReader:public String readLine(): 读一行文字。
  • BufferedWriter:public void newLine(): 写一行行分隔符,由系统属性定义符号。

readLine方法演示,代码如下:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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方法演示,代如下:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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 练习:文本排序

请将文本信息恢复顺序。

text
1
2
3
4
5
6
7
8
9
3.侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉以咨之,然后施行,必得裨补阙漏,有所广益。
8.愿陛下托臣以讨贼兴复之效,不效,则治臣之罪,以告先帝之灵。若无兴德之言,则责攸之、祎、允等之慢,以彰其咎;陛下亦宜自谋,以咨诹善道,察纳雅言,深追先帝遗诏,臣不胜受恩感激。
4.将军向宠,性行淑均,晓畅军事,试用之于昔日,先帝称之曰能,是以众议举宠为督。愚以为营中之事,悉以咨之,必能使行阵和睦,优劣得所。
2.宫中府中,俱为一体,陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。
1.先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。
9.今当远离,临表涕零,不知所言。
6.臣本布衣,躬耕于南阳,苟全性命于乱世,不求闻达于诸侯。先帝不以臣卑鄙,猥自枉屈,三顾臣于草庐之中,咨臣以当世之事,由是感激,遂许先帝以驱驰。后值倾覆,受任于败军之际,奉命于危难之间,尔来二十有一年矣。
7.先帝知臣谨慎,故临崩寄臣以大事也。受命以来,夙夜忧叹,恐付托不效,以伤先帝之明,故五月渡泸,深入不毛。今南方已定,兵甲已足,当奖率三军,北定中原,庶竭驽钝,攘除奸凶,兴复汉室,还于旧都。此臣所以报先帝而忠陛下之职分也。至于斟酌损益,进尽忠言,则攸之、祎、允之任也。
5.亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。先帝在时,每与臣论此事,未尝不叹息痛恨于桓、灵也。侍中、尚书、长史、参军,此悉贞良死节之臣,愿陛下亲之信之,则汉室之隆,可计日而待也。

1.4.1 案例分析

  1. 逐行读取文本信息。
  2. 解析文本信息到集合中。
  3. 遍历集合,按顺序,写出文本信息。

1.4.2 案例实现

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Demo05TextSort {
	public static void main(String[] args) {
		Map<String,String> map=new HashMap<String,String>();
		try(BufferedReader br=new BufferedReader(new FileReader("src\\demo36\\text.txt"));
				BufferedWriter bw=new BufferedWriter(new FileWriter("src\\demo36\\textSort.txt"))){
			String s="";
			while((s=br.readLine())!=null) {
				String[] arr=s.split("\\.");
				map.put(arr[0], arr[1]);
			}
			for(String key:map.keySet()) {
				bw.write(key+"."+map.get(key));
				bw.newLine();
			}
			
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}

第二章 转换流

2.1 字符编码和字符集

2.1.1 字符编码

计算机中储存的信息都是用二进制数表示的,而我们在屏幕上看到的数字、英文、标点符号、汉字等字符是二进制数转换之后的结果。按照某种规则,将字符存储到计算机中,称为编码 。反之,将存储在计算机中的二进制数按照某种规则解析显示出来,称为解码

比如说,按照A规则存储,同样按照A规则解析,那么就能显示正确的文本符号。反之,按照A规则存储,再按照B规则解析,就会导致乱码现象。

编码:字符(能看懂的)--字节(看不懂的)

解码:字节(看不懂的)-->字符(能看懂的)

  • 字符编码Character Encoding : 就是一套自然语言的字符与二进制数之间的对应规则。

    编码表:生活中文字和计算机中二进制的对应规则

2.1.2 字符集

  • 字符集 Charset:也叫编码表。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等。

计算机要准确的存储和识别各种字符集符号,需要进行字符编码,一套字符集必然至少有一套字符编码。常见字符集有ASCII字符集、GBK字符集、Unicode字符集(u8,u16,u32)等。

1_charset.jpg

可见,当指定了编码,它所对应的字符集自然就指定了,所以编码才是我们最终要关心的。

  • 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 编码引出的问题

FileReader读取项目IDE的默认编码。当读取windows系统中的文本文件时,采用的是系统的编码。如果两者不统一,就会出现问题。

**编码:**字符(能看懂的)--字节(看不懂的)

**解码:**字节(看不懂的)-->字符(能看懂的)

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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): 创建一个指定字符集的字符流。

使用步骤:

  1. 创建InputStreamReader对象,构造方法中传递字节输入流,和指定的编码表名称

  2. 使用InputStreamReader对象中的方法read读取文件

  3. 释放资源

注意事项:

构造方法中指定的编码表名称要和文件的编码相同,否则会发生乱码

构造举例,代码如下:

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

指定编码读取

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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): 创建一个指定字符集的字符流。

使用步骤:

  1. 创建一个OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称

  2. 使用OutputStreamWriter对象中的方法write,把字符转换成字节存储到缓冲区中(编码的过程)

  3. 使用OutputStreamWriter对象中的flush,把内存缓冲区的字节刷新到文件中(使用字节流写字节的过程)

  4. 释放资源

构造举例,代码如下:

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

指定编码写出

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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 转换流理解图解

转换流是字节与字符间的桥梁!

2_zhuanhuan.jpg

2.6 练习:转换文件编码

将GBK编码的文本文件,转换为UTF-8编码的文本文件。

2.6.1 案例分析

  1. 指定GBK编码的转换流,读取文本文件。
  2. 使用UTF-8编码的转换流,写出文本文件。

2.6.2 案例实现

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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_xuliehua.jpg

3.2 ObjectOutputStream类

java.io.ObjectOutputStream 类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。

构造方法

  • public ObjectOutputStream(OutputStream out) : 创建一个指定OutputStream的ObjectOutputStream。

使用步骤:

  1. 创建一个ObjectOutputStream对象,构造方法中传递字节输出流

  2. 使用ObjectOutputStream对象中的方法writeObject,把对象写入到文件中

  3. flush

  4. close

构造举例,代码如下:

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

序列化操作

  1. 一个对象要想序列化,必须满足两个条件:
  • 该类必须实现java.io.Serializable 接口,Serializable 是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出NotSerializableException
  • 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用transient 关键字修饰。
java
1
2
3
4
5
6
7
8
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) : 将指定的对象写出。
java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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. 创建一个ObjectInputStream对象,构造方法中传递字节输入流

  2. 使用ObjectInputStream对象中的readObject方法,读取保存对象的文件

  3. 释放资源

  4. 使用读取出来的对象

反序列化操作1

如果能找到一个对象的class文件,我们可以进行反序列化操作,调用ObjectInputStream读取对象的方法:

  • public final Object readObject () : 读取一个对象。
java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 该版本号的目的在于验证序列化的对象和对应类是否版本匹配。

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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 序列化过程描述

类实现了Serializable接口,就会根据类的定义,给Person.class文件,添加一个序列号。如果修改了类的定义,那么就会给Person.class文件中的序列号和Person.text文件中的序列号进行比较。

如果是一样的,则反序列化成功;如果不一样,则抛出序列化冲突异常InvalidClassException

解决方法:

无论是否对类的定义进行修改,都不重新生成序列号,可以手动给类添加一个序列号

格式:

在Serializable接口规定,可序列化类可以通过声明serialVersionUID的字段(static,final,long型的),显示声明其自己的serialVersionUID

java
1
static final long serialVersionUID=42L;

3.5 static与transient关键字比较

static关键字:静态关键字

静态优先于非静态加载到内存中(优先于对象进入到内存中),被static修饰的成员变量是不能被序列化的,序列化的都是对象。

transient关键字:瞬态关键字

被transient修饰的成员变量,不能被序列化。最终实现的效果跟static类似,但是没有static的含义。

比较:

将变量注释为static或者transient运行一下序列化和反序列化的程序,进行结果比较

3.6 练习:序列化集合

  1. 将存有多个自定义对象的集合序列化操作,保存到list.txt文件中。
  2. 反序列化list.txt ,并遍历集合,打印对象信息。

3.6.1 案例分析

  1. 把若干学生对象 ,保存到集合中。
  2. 把集合序列化。
  3. 反序列化读取时,只需要读取一次,转换为集合类型。
  4. 遍历集合,可以打印所有的学生信息

3.6.2 案例实现

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Demo07Practice {
	public static void main(String[] args) {
		write();
		read();
	}

	public static void write() {
		ArrayList<Person> list = new ArrayList<Person>();
		list.add(new Person("水月儿", 18));
		list.add(new Person("邱若水", 19));
		list.add(new Person("水冰儿", 20));
		try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src\\demo37\\demo07.txt"))) {
			oos.writeObject(list);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("success");
	}

	public static void read() {
		ArrayList<Person> list = new ArrayList<Person>();
		try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\demo37\\demo07.txt"))) {
			list = (ArrayList<Person>) ois.readObject();
			for (Person p : list) {
				System.out.println(p.getName() + " " + p.getAge());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

第四章 打印流

4.1 概述

平时我们在控制台打印输出,是调用print方法和println方法完成的,这两个方法都来自于java.io.PrintStream类,该类能够方便地打印各种数据类型的值,是一种便捷的输出方式。

4.2 PrintStream类

4.2.1 构造方法

  • public PrintStream(String fileName) : 使用指定的文件名创建一个新的打印流。

构造举例,代码如下:

java
1
PrintStream ps = new PrintStream("ps.txt")

4.2.2 改变打印流向

System.out就是PrintStream类型的,只不过它的流向是系统规定的,打印在控制台上。不过,既然是流对象,我们就可以玩一个"小把戏",改变它的流向。

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Demo09PrintStream {
	public static void main(String[] args) throws FileNotFoundException {
		System.out.println("我是在控制台输出的");
		
		PrintStream ps=new PrintStream("src\\demo37\\demo09.txt");
		System.setOut(ps);
		System.out.println("我是在文件中输出的");
		ps.close();
	}
}