博客
关于我
day10【缓冲流、转换流、序列化流、打印流】
阅读量:366 次
发布时间:2019-03-03

本文共 7298 字,大约阅读时间需要 24 分钟。

Java IO流深度探索:缓冲流、转换流及序列化与打印流实践指南

主要内容

Java IO流系统是Java编程的重要组成部分,涵盖了文件读写、数据传输等多个核心功能。作为开发者,掌握高级IO流的使用方法至关重要。本文将深入探讨Java中的缓冲流、转换流、序列化流以及打印流,帮助开发者更高效地处理IO操作。


教学目标

  • 能够使用字节缓冲流读取数据到程序
  • 能够使用字节缓冲流写出数据到文件
  • 能够明确字符缓冲流的作用和基本用法
  • 能够使用缓冲流的特殊功能
  • 能够阐述编码表的意义
  • 能够使用转换流读取指定编码的文本文件
  • 能够使用转换流写入指定编码的文本文件
  • 能够说出打印流的特点
  • 能够使用序列化流写出对象到文件
  • 能够使用反序列化流读取文件到程序中

  • 第一章 缓冲流

    1.1 概述

    缓冲流(BufferedInputStream/BufferedOutputStream)是一种高效流,它通过在内存中创建一个缓冲区,减少系统IO操作的次数,从而提高读写效率。缓冲流的主要分类如下:

    • 字节缓冲流:BufferedInputStream/BufferedOutputStream
    • 字符缓冲流:BufferedReader/BufferedWriter

    缓冲流的工作原理是,在流对象创建时,会预先分配一个默认大小的缓冲区。读取或写入数据时,先将数据放入缓冲区,再批量处理,从而提升性能。


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

    效率测试

    通过测试发现,使用缓冲流处理大文件比普通流快得多。以下是两种流的效率对比:

    普通流

    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) + "毫秒");    }}

    缓冲流优化示例

    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) + "毫秒");    }}

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

    特有方法

    • readLine(): 读取一行文本。
    • newLine(): 写入换行符。

    代码示例

    读取一行文本

    public class BufferedReaderDemo {    public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new FileReader("in.txt"));        String line = null;        while ((line = br.readLine()) != null) {            System.out.print(line);            System.out.println("------");        }        br.close();    }}

    写入换行符

    public class BufferedWriterDemo {    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 练习:文本排序

    案例分析

  • 逐行读取文本信息。
  • 解析文本信息到集合中。
  • 按顺序写出文本信息。
  • 案例实现

    public class BufferedTest {    public static void main(String[] args) throws IOException {        HashMap
    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(); for (int i = 1; i <= lineMap.size(); i++) { String key = String.valueOf(i); String value = lineMap.get(key); bw.write(key + "." + value); bw.newLine(); } bw.close(); }}

    第二章 转换流

    2.1 字符编码与字符集

    字符编码是将字符转换为二进制数的过程,字符集则包含了系统支持的所有字符。常见编码表包括ASCII、ISO-8859-1、GB2312、GBK和Unicode等。


    2.2 InputStreamReader类

    InputStreamReader 是字节流与字符流之间的桥梁,用于指定编码读取文本文件。

    代码示例

    // 读取GBK编码文件InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\File_GBK.txt"), "GBK");

    读取示例

    public class ReaderDemo {    public static void main(String[] args) throws IOException {        String fileName = "E:\\File_GBK.txt";        InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName), "GBK");        int read;        while ((read = isr.read()) != -1) {            System.out.print((char) read);        }        isr.close();    }}

    2.3 OutputStreamWriter类

    OutputStreamWriter 是字符流与字节流之间的桥梁,用于指定编码写出文本文件。

    代码示例

    // 写入UTF-8编码文件OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\\out.txt"), "UTF-8");osw.write("你好");osw.close();

    2.4 转换流理解

    转换流是字节流与字符流之间的桥梁,用于处理不同编码的文件。


    第三章 序列化

    3.1 概述

    Java 提供了强大的对象序列化机制,允许将Java对象保存为字节序列,实现持久化存储。


    3.2 ObjectOutputStream类

    构造方法

    • public ObjectOutputStream(OutputStream out)

    代码示例

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

    注意事项

    • 实现Serializable接口。
    • 瞬态字段使用transient修饰。

    3.3 ObjectInputStream类

    构造方法

    • public ObjectInputStream(InputStream in)

    反序列化示例

    ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.txt"));Employee e = (Employee) in.readObject();in.close();

    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
    list = new ArrayList<>(); list.add(student); list.add(student2); list.add(student3); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt")); oos.writeObject(list); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list.txt")); ArrayList
    list = (ArrayList
    ) ois.readObject(); for (int i = 0; i < list.size(); i++) { Student s = list.get(i); System.out.println(s.getName() + "--" + s.getPwd()); } }}

    第四章 打印流

    4.1 概述

    打印流(PrintStream)提供了一个高效的方式来向标准输出或文件打印文本。


    4.2 PrintStream类

    构造方法

    • public PrintStream(String fileName)

    代码示例

    PrintStream ps = new PrintStream("ps.txt");System.setOut(ps);System.out.println(97);

    4.3 改变打印流向

    通过System.setOut()方法,可以将打印流的目标文件更改为指定文件或其他流。


    通过本章的学习,你应该能够熟练使用Java中的缓冲流、转换流、序列化流和打印流,提升日常开发中的IO操作效率。

    转载地址:http://jelm.baihongyu.com/

    你可能感兴趣的文章
    mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
    查看>>
    Mysql8 数据库安装及主从配置 | Spring Cloud 2
    查看>>
    mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
    查看>>
    MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
    查看>>
    MYSQL8.0以上忘记root密码
    查看>>
    Mysql8.0以上重置初始密码的方法
    查看>>
    mysql8.0新特性-自增变量的持久化
    查看>>
    Mysql8.0注意url变更写法
    查看>>
    Mysql8.0的特性
    查看>>
    MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
    查看>>
    MySQL8修改密码的方法
    查看>>
    Mysql8在Centos上安装后忘记root密码如何重新设置
    查看>>
    Mysql8在Windows上离线安装时忘记root密码
    查看>>
    MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
    查看>>
    mysql8的安装与卸载
    查看>>
    MySQL8,体验不一样的安装方式!
    查看>>
    MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
    查看>>
    Mysql: 对换(替换)两条记录的同一个字段值
    查看>>
    mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
    查看>>
    MYSQL:基础——3N范式的表结构设计
    查看>>