Java基础——IO流

IO流概述

什么是流?

流是有起点和终点的有序字节序列的集合。

流的分类

  • 输入流/输出流:流根据方向可以分为输入流与输出流,输入与输出是相对于内存而言的,从内存村来就是输出,到内存中就是输入。
  • 字节流/字符流:流根据读取数据的方式可以分为字节流与字符流,字节流是按照字节的方式读取,字符流是按照字符的方式读取,一次读取2个字节(Java中1个字符占2个字节)。
  • 节点流/处理流:如果直接从设备上读写数据就是节点流; 处理流是对节点流的包装。

流的作用就是读写设备上的数据,在java.io包中定义了相关的流类,以Stream结尾的是字节流,以Reader、Writer结尾的是字符输入/出流。

流的使用

  • 流的继承关系

  • 文件字节输入/出流FileInputStream/FileOutputStream

通过字节输出流与字节输入流完成文件的复制。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test04 {
    public static void main(String[] args) {

        //创建字节输入流与输出流
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //分别指定对应的文件
            fis = new FileInputStream("F:/a.txt");
            fos = new FileOutputStream("F:/a_copy.txt");

            //设定每次读取1MB
            byte[] bytes = new byte[1024*1024];
            int temp = 0;

            //循环读取并输出到新的文件中,实现文件的复制
            //read()是读取文件的方法,temp是读取到缓冲区的字节总量,返回-1表示以读取到文件的末尾
            while ((temp = fis.read(bytes)) != -1){
                fos.write(bytes, 0, temp);
            }

            //刷洗字节输出流,强制将缓冲区的字节写出
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //最后要关闭字节输入流与输出流
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 文件字符输入/出转换流InputStreamReader/OutputStreamWriter

字符输入/输出流FileReader/FileWriter基本与字节流相同,但是因为是以字符为单位处理流中的数据,所以只能读写纯文本文件,且要求文本文件的编码格式与当前环境的编码格式一致。

文本文件与当前环境编码格式不兼容时,使用转换流,可以指定编码格式。

import java.io.*;

public class Test05 {
    public static void main(String[] args) {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;

        try {
            //创建转换流,构造函数的参数有两个,第一个是字符输入流,第二个是编码格式
            isr = new InputStreamReader(new FileInputStream("F:/a.txt"), "gbk");
            osw = new OutputStreamWriter(new FileOutputStream("F:/a.copy.txt"));

            //字符流是以字符为单位读写数据的,所以这里要用char数组
            char[] chars = new char[1024 * 1024];
            int temp = 0;
            while ((temp = isr.read(chars)) != -1) {
                osw.write(chars, 0, temp);
            }
            osw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 缓冲字节输入/出流BufferedInputStream/BufferedOutputStream

这是带有缓冲区的字节流,属于处理流,与缓冲字符流基本相同。

  • 缓冲字符输入/出流BufferedReader/BufferedWriter

import java.io.*;

public class Test06 {
    public static void main(String[] args) {
        BufferedReader bir = null;
        BufferedWriter bow = null;

        try {
            bir = new BufferedReader(new InputStreamReader(new FileInputStream("F:/a.txt"), "gbk"));
            bow = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:/a_copy.txt")));

            String temp = null;
            //使用BufferedReader时有一种方法readLine可以读取一行,返回值是对应的一行字符串
            while ((temp = bir.readLine()) != null){
                bow.write(temp);
            }
            bow.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bir.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bow.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 数据字节输入/出流DataInputStream/DataOutputStream

数据字节输入/出流,在写入硬盘中时,写进去的不是字符串而是带有类型的二进制数据。

import java.io.*;

public class Test07 {
    public static void main(String[] args) {
        DataOutputStream dos = null;
        DataInputStream dis = null;

        try {
            dos = new DataOutputStream(new FileOutputStream("F:/data.txt"));
            //写入的数据带有类型
            int a1 = 9;
            char a2 = '流';
            Double a3 = 9.12;

            dos.writeInt(a1);
            dos.writeChar(a2);
            dos.writeDouble(a3);

            //在读取数据时必须按照对应的类型读取
            dis = new DataInputStream(new FileInputStream("F:/data.txt"));
            System.out.println(dis.readInt());
            System.out.println(dis.readChar());
            System.out.println(dis.readDouble());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

这是写入的文件中的内容,无法查看具体内容。

 

  • 打印流PrintStream/PrintWriter

打印流,默认输出到控制台,可以改变输出方向,可以用来记录日志(当然现在都用log4j)。

import java.io.FileNotFoundException;
import java.io.PrintStream;

public class Test08 {
    public static void main(String[] args) {
        //这两个输出效果相同,都是输出到控制台
        System.out.println("打印流");
        PrintStream ps = System.out;
        ps.println("PrintStream");
        
        //改变打印流的输出方向,输出到硬盘中的log.txt文件中
        try {
            System.setOut(new PrintStream("F:/log.txt"));
            System.out.println("改变了打印流的方向");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

控制台中只有前两种的输出。

最后的输出在文件中。

  • 序列化/发序列化ObjectOutputStream/ObjectInputStream

ObjectOutputStream是将对象转换为二进制序列保存到文件中,ObjectInputStream是将二进制序列转换为对象。

序列化/反序列化的条件是对象类要实现Serializable接口。

Serializable是一个接口,其中没有任何方法,实现Serializable接口后要手动添加一个序列化版本号SerialVersionUID。

最好不要使用系统自动生成的SerialVersionUID,因为当对象类结构发生了修改后系统会重新生成一个SerialVersionUID,在反序列化时两个SerialVersionUID不一致会出现异常。

在不想参加序列化的字段前可以加关键字transient。

先准备一个类实现Serializable接口,在age字段上使用transient关键字。

import java.io.Serializable;

public class Person implements Serializable {
    static final long serialVersionUID = 9L;

    private int id;
    private String name;
    private  boolean isMarried;
    private transient int age;

    public Person(int id, String name, boolean isMarried, int age) {
        this.id = id;
        this.name = name;
        this.isMarried = isMarried;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isMarried() {
        return isMarried;
    }

    public void setMarried(boolean married) {
        isMarried = married;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", isMarried=" + isMarried +
                ", age=" + age +
                '}';
    }
}

以下是序列化与发序列化的代码

import java.io.*;

public class Test09 {
    public static void main(String[] args) {
        //创建一个Person对象
        Person p1 = new Person(12, "autumn", false, 23);
        Person p2 = new Person(9, "winter", false, 23);

        ObjectOutputStream oos =null;
        ObjectInputStream ois = null;
        //
        try {
            oos = new ObjectOutputStream(new FileOutputStream("F:/person.txt"));
            oos.writeObject(p1);
            oos.writeObject(p2);

            ois = new ObjectInputStream(new FileInputStream("F:/person.txt"));
            Object o = null;
            for (int i=0; i<2; i++){
                System.out.println(ois.readObject());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

控制台的输出为

因为age字段上使用了transient关键字,因此没有参与序列化。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值