Java高级重点知识点-22-缓冲流、转换流、序列化流、打印流

缓冲流

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

字节缓冲流

构造方法

  • public BufferedInputStream(InputStream in) :创建一个 新的缓冲输入流
  • public BufferedOutputStream(OutputStream out) : 创建一个新的缓冲输出流。

通过读入一个程序与写出一个程序来举例缓冲流的使用方法。
首先准备一个较大的压缩包文件,放在了D:\file1\java.zip,这个路径下面。
在这里插入图片描述
使用缓冲流读写数据:

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // 记录开始时间
        long start = System.currentTimeMillis();
        // 创建流对象
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\file1\\java.zip"));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\file2\\javaCopy.zip"));
        ) {
            // 读写数据
            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) + " 毫秒");
    }
}

在这里插入图片描述
使用基本流读写数据:

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // 记录开始时间
        long start = System.currentTimeMillis();
        // 创建流对象
        try (
                FileInputStream fis = new FileInputStream("D:\\file1\\java.zip");
                FileOutputStream fos = new FileOutputStream("D:\\file2\\javaCopy.zip")
        ) {
        // 读写数据
            int b;
            while ((b = fis.read()) != -1){
                fos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 记录结束时间
        long end = System.currentTimeMillis();
        System.out.println("普通流复制时间:" + (end - start) + " 毫秒");
    }
}

在这里插入图片描述
从这里我们可以看到普通流对象读写数据与缓冲流(高效流)读取数据的差异性了,高效流通过一次读入多个数据到缓冲区,然后一次读出,减少IO操作,提高了读写效率。

字符缓冲流

在D:\file1目录下面创建一个in.txt文件。
在这里插入图片描述

构造方法

  • public BufferedReader(Reader in) :创建一个 新的缓冲输入流
  • public BufferedWriter(Writer out) : 创建一个新的缓冲输出流。

特殊方法

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

代码示例:

public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        // 创建流对象
        BufferedReader br = new BufferedReader(new FileReader("D:\\file1\\in.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\file3\\out.txt"));
        // 定义字符串,保存读取的一行文字
        String line = null;
        // 循环读取,读取到最后返回null
        while ((line = br.readLine()) != null) {
            bw.write(line, 0, line.length());
            bw.newLine();
        }
        // 释放资源
        bw.close();
        br.close();
    }
}

在这里插入图片描述

转换流

  1. 字符编码和字符集

将字符存储到计算机中,称为编码,反之,将存储在计算机中的二进制数按照某种规则解析显示出来,称为解码 。

  • 字符编码 Character Encoding : 就是一套自然语言的字符与二进制数之间的对应规则。
  • 字符集 Charset :也叫编码表。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等。

常见的字符集:

  • ASCII字符集 :ASCII(American Standard Code for Information Interchange,美国信息交换标准代码)是基于拉丁字母的一套电脑编码系统
  • ISO-8859-1字符集:拉丁码表,别名Latin-1,用于显示欧洲使用的语言
  • GBxxx字符集:GB就是国标的意思,是为了显示中文而设计的一套字符集。
  • Unicode字符集 :Unicode编码系统为表达任意语言的任意字符而设计,是业界的一种标准,也称为统一码、标准万国码。

问题引入:
准备一个D:\file\in.txt文件
在这里插入图片描述

public class ReaderDemo {
    public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("D:\\file1\\in.txt");
        int read;
        while ((read = fileReader.read()) != -1) {
            System.out.print((char)read);
        }
        fileReader.close();
    }
}

在这里插入图片描述
出现了中文乱码,这是因为Windows系统的默认是GBK编码,就会出现乱码。这个编码问题我们可以通过转换流来解决。

InputStreamReader类

转换流 java.io.InputStreamReader ,是Reader的子类,是从字节流到字符流的桥梁。
构造方法:

  • InputStreamReader(InputStream in) : 创建一个使用默认字符集的字符流。
  • InputStreamReader(InputStream in, String charsetName) : 创建一个指定字符集的字符流。
package demo10;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReaderDemo2 {
    public static void main(String[] args) throws IOException {
        // 定义文件路径,文件为gbk编码
        String FileName = "D:\\file1\\in.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();
        System.out.println();
        // 使用指定编码字符流读取,正常解析
        while ((read = isr2.read()) != -1) {
            System.out.print((char)read);
        }
        isr2.close();
    }
}

在这里插入图片描述
这里我们使用了俩种构造方法来创建我们的InputStreamReader对象,当我们指定了解码采用GBK格式来对我们的in.txt进行解码时,可以看到我们输出的字符是正常的而不是乱码。

OutputStreamWriter类

转换流 java.io.OutputStreamWriter ,是Writer的子类,是从字符流到字节流的桥梁。
构造方法:

  • OutputStreamWriter(OutputStream in) : 创建一个使用默认字符集的字符流。
  • OutputStreamWriter(OutputStream in, String charsetName) : 创建一个指定字符集的字符流。
import java.io.*;

public class TransDemo {
    public static void main(String[] args) throws IOException {
        // 1.定义文件路径
        String srcFile = "D:\\file1\\in.txt";
        String destFile = "D:\\file3\\out.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 提供了一种对象序列化的机制。用一个字节序列可以表示一个对象,该字节序列包含该对象的数据、对象的 类型和对象中存储的属性等信息。

  • 反序列化: 从文件中读取字节序列,重构对象

序列化流理解图解:
在这里插入图片描述

ObjectOutputStream类

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

序列化条件:

  • 该类必须实现 java.io.Serializable 接口, Serializable 是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出 NotSerializableException 。
  • 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用transient 关键字修饰。
import java.io.Serializable;

public class Employee implements Serializable {
    public String name;
    public String address;
    public transient int age; // transient瞬态修饰成员,不会被序列化
    public void addressCheck() {
        System.out.println("Address check : " + name + " ‐‐ " + address);
    }
}

员工类实现类Serializable接口,表示该类可以进行序列化操作,该类中的age属性修饰了transient(瞬态)代表该字段不会被序列化。

如何进行序列化:
创建一个D:\file2目录。
在这里插入图片描述

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeDemo{
    public static void main(String [] args) {
        Employee e = new Employee();
        e.name = "huge";
        e.address = "huangshi";
        e.age = 20;
        try {
            // 创建序列化流对象
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\file2\\employee.txt"));
            // 写出对象
            out.writeObject(e);
            // 释放资源
            out.close();
            System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。
        } catch(IOException i) {
            i.printStackTrace();
        }
    }
}

在这里插入图片描述
我们可以看到对象已经被序列化到了指定文件之中。那么我们这么进行反序列化来检查我们是否序列化成功呢?那就要使用到ObjectInputStream类了。

ObjectInputStream类

ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeDemo {

    public static void main(String [] args) {
        Employee e = null;
        try {
            // 创建反序列化流
            FileInputStream fileIn = new FileInputStream("D:\\file2\\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); // huge
        System.out.println("Address: " + e.address); // huangshi
        System.out.println("age: " + e.age); // 0
    }
}

在这里插入图片描述
通过控制台显示数据我们可以看到我们进行序列化的对象是正确的。
反序列化失败情况:

  • 该类的序列版本号与从流中读取的类描述符的版本号不匹配
  • 该类包含未知数据类型
  • 该类没有可访问的无参数构造方法

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

打印流

java.io.PrintStream 类,该类能够方便地打印各种数据类型的值
构造方法:

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

改变流向:
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);
}
}
在这里插入图片描述
我们可以看到我们的数据输出的流向通过System.setOut(ps);改变了,输出到D:\file3\out.txt中了。(日志输出相似

欢迎java热爱者了解文章,作者将会持续更新中,期待各位友友的关注和收藏,另外对编程感兴趣的友友们可以加以下群共同学习。群号:127871664

  • 24
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿胡爱编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值