IO流(下)

一、缓冲流

1、缓冲流涉及到的类:

  • BufferedInputStream
  • BufferedOutputStream
  • BufferedReader
  • BufferedWriter

2、引入目的

  • 作用:提高流的读取、写入的速度

  • 提高读写速度的原因:内部提供了一个缓冲区的内存中。从内存中读取的速度要高于直接从硬盘中读取的速度。

3、使用说明

  • 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。

  • 当使用 BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。

  • 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流。

  • 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流。

  • flush()方法的使用:手动将buffer中内容写入文件。

  • 如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出。

4、使用BufferedReader和BufferedWriter实现文本文件的复制

@Test
public void testBufferedReaderBufferedWriter(){
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        //创建文件和相应的流
        br = new BufferedReader(new FileReader(new File("dbcp.txt")));
        bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
        //读写操作
        //方式一:使用char[]数组
        //            char[] cbuf = new char[1024];
        //            int len;
        //            while((len = br.read(cbuf)) != -1){
        //                bw.write(cbuf,0,len);
        //                bw.flush();
        //            }

        //方式二:使用String(字节流就不行了)
        String data;
        while((data = br.readLine()) != null){
            //方法一:
            //bw.write(data);//data中不包含换行符,(data + "\n") 写成这样就可以换行了
            //方法二:
            bw.write(data);
            bw.newLine();//提供换行的操作
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //关闭资源
        if(bw != null){

            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(br != null){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}

练习:实现图片加密操作

  • 将图片文件通过字节流读取到程序中
  • 将图片的字节流逐一进行^操作(异或操作)
  • 将处理后的图片字节流输出
@Test
public void test1() {

    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream("test.jpg");
        fos = new FileOutputStream("testSecret.jpg");

        byte[] buffer = new byte[20];
        int len;
        while ((len = fis.read(buffer)) != -1) {

            for (int i = 0; i < len; i++) {
                buffer[i] = (byte) (buffer[i] ^ 5);//加密
            }

            fos.write(buffer, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

解密操作

  • 将加密后图片文件通过字节流读取到程序中
  • 将图片的字节流逐一进行^操作(原理:A^B^B = A)
  • 将处理后的图片字节流输出

二、转换流

  • 转换流提供了在字节流和字符流之间的转换

  • 字节流中的数据都是字符时,转成字符流操作更高效。

  • 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

1、InputStreamReader

将一个字节的输入流转换为字符的输入流 解码:字节、字节数组 --->字符数组、字符串

构造器:

  • public InputStreamReader(InputStream in)

  • public InputStreamReader(Inputstream in,String charsetName)//可以指定编码集

2、OutputStreamWriter

 

将一个字符的输出流转换为字节的输出流 编码:字符数组、字符串 ---> 字节、字节数组

构造器:

  • public OutputStreamWriter(OutputStream out)

  • public OutputStreamWriter(Outputstream out,String charsetName)//可以指定编码集

image-20200502114233303

@Test
public void test1() {
    InputStreamReader isr = null;
    OutputStreamWriter osw = null;
    try {
        //1.造文件、造流
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_gbk.txt");

        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);

        isr = new InputStreamReader(fis, "utf-8");
        osw = new OutputStreamWriter(fos, "gbk");

        //2.读写过程
        char[] cbuf = new char[20];
        int len;
        while ((len = isr.read(cbuf)) != -1){
            osw.write(cbuf,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.关流
        if (isr != null){

            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (osw != null){
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

说明:文件编码的方式(比如:GBK),决定了解析时使用的字符集(也只能是GBK)。

三、标准输入、输出流

1、简介

System.in:标准的输入流(字节流),默认从键盘输入

System.out:标准的输出流,默认从控制台输出

2、主要方法

System类的setIn(InputStream is) 方式重新指定输入的流

System类的setOut(PrintStream ps)方式重新指定输出的流。

3、案例,实现一个Scanner类

我们需要读取键盘上的字符,我们可以先转换成字符流:System.in ---> 转换流 ---> BufferedReader的readLine()

public class MyInput {
    //从键盘上读取
    public static String readString() {
        //InputStreamReader isr = new InputStreamReader(System.in);
        //BufferedReader br = new BufferedReader(isr);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String string = "";
        //从键盘输入读取一行
        try {
            string = br.readLine();

        } catch (IOException ex) {
            System.out.println(ex);
        }
        return string;
    }

    //读取int
    public static int readInt() {
        return Integer.parseInt(readString());
    }
    //double
    public static double readDouble() {
        return Double.parseDouble(readString());
    }
    //float
    public static double readFloat() {
        return Float.parseFloat(readString());
    }
    ...
}

四、打印流

PrintStream 和 PrintWriter 说明:

  • 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
  • System.out返回的是PrintStream的实例

案例:在指定文件打印ASCII字符

public void test() {
    PrintStream ps = null;//输出流
    try {
        FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
        // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
        ps = new PrintStream(fos, true);
        if (ps != null) {
            System.setOut(ps);// 把标准输出流(控制台输出)改成文件
        }

        for (int i = 0; i <= 255; i++) { // 输出ASCII字符
            System.out.print((char) i);
            if (i % 50 == 0) { // 每50个数据一行
                System.out.println(); // 换行
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (ps != null) {
            ps.close();
        }
    }
}

五、对象流

1、对象流:

ObjectInputStream 和 ObjectOutputStream

2、作用

  • ObjectOutputStream:内存中的对象--->存储中的文件、通过网络传输出去:序列化过程
  • ObjectInputStream:存储中的文件、通过网络接收过来 --->内存中的对象:反序列化过程

3、对象的序列化(#####)

  • 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。

  • 序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原。

  • 序列化是RMI(Remote Method Invoke-远程方法调用)过程的参数和返回值都必须实现的机制,RMI是JavaEE的基础。因此序列化机制是JavaEE平台的基础。

  • 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。否则,会抛出 NotserializableEXception异常

    • Serializable
    • Externalizable
  • 凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:

    • private static final long serialVersionUID;
    • serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容
    • 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID可能发生变化。故建议显式声明。
  • 简单来说,Java的序列化机制是通过在运行时判断类的serialversionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialversionUID与本地相应实体类的serialversionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。(InvalidCastException)

4、实现序列化满足的条件

  • 需要实现接口:Serializable(标识接口)

  • 当前类提供一个全局常量:serialVersionUID(序列版本号)

  • 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)

补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量

5、序列化代码

public void test(){
    ObjectOutputStream oos = null;

    try {
        //1.创建对象,创建流
        oos = new ObjectOutputStream(new FileOutputStream("object.data"));
        //2.操作流
        oos.writeObject(new String("我爱北京天安门"));
        oos.flush();//刷新操作

        oos.writeObject(new Person("vv",23));//Person是可序列化的 
        oos.flush();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(oos != null){
            //3.关闭流
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}

6、反序列化代码

public void test2(){
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("object.data"));

        Object obj = ois.readObject();
        String str = (String) obj;

        Person p = (Person) ois.readObject();

        System.out.println(str);//我爱北京天安门
        System.out.println(p);//

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if(ois != null){
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

六、任意存取文件流,RandomAccessFile

1、简介

  • RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口

  • RandomAccessFile既可以作为一个输入流,又可以作为一个输出流

  • RandomAccessFile类支持“随机访问”的方式,程序可以直接跳到文件的任意地方来读、写文件

    • 支持只访问文件的部分内容
    • 可以向已存在的文件后追加内容
  • RandomAccessFile对象包含一个记录指针,用以标示当前读写处的位置

  • RandomaccessFile类对象可以自由移动记录指针:

    • long getFilePointer():获取文件记录指针的当前位置
    • void seek(long pos):将文件记录指针定位到pos位置

构造器

public RandomAccessFile(File file,String mode)

public RandomAccessFile(String name,String mode)

2、使用说明

  • 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
  • 如果写出到的文件存在,则会对原文件内容进行覆盖。(默认情况下,从头覆盖)
  • 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果。借助seek(int pos)方法
  • 创建RandomAccessFile类实例需要指定一个mode参数,该参数指定RandomAccessFile的访问模式:
    • r:以只读方式打开
    • rw:打开以便读取和写入
    • rwd:打开以便读取和写入;同步文件内容的更新
    • rws:打开以便读取和写入;同步文件内容和元数据的更新
  • 如果模式为只读r,则不会创建文件,而是会去读取一个已经存在的文件,读取的文件不存在则会出现异常。如果模式为rw读写,文件不存在则会去创建文件,存在则不会创建。

3、使用RandomAccessFile实现数据的在文本3的位置插入"xyz"

public void test(){
    RandomAccessFile raf1 = null;
    try {
        raf1 = new RandomAccessFile(new File("hello.txt"), "rw");

        raf1.seek(3);//将指针调到角标为3的位置
        //            //方式一
        //            //保存指针3后面的所有数据到StringBuilder中
        //            StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
        //            byte[] buffer = new byte[20];
        //            int len;
        //            while ((len = raf1.read(buffer)) != -1){
        //                builder.append(new String(buffer,0,len));
        //            }

        //方式二
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[20];
        int len;
        while ((len = raf1.read(buffer)) != -1){
            baos.write(buffer);
        }
        //调回指针,写入“xyz”
        raf1.seek(3);
        raf1.write("xyz".getBytes());
        //将StringBuilder中的数据写入到文件中
        raf1.write(baos.toString().getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (raf1 != null){
            try {
                raf1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

七、流的基本应用总结

  • 流是用来处理数据的。

  • 处理数据时,一定要先明确数据源,与数据目的地数据源可以是文件,可以是键盘数据目的地可以是文件、显示器或者其他设备

  • 而流只是在帮助数据进行传输,并对传输的数据进行处理,比如过滤处理、转换处理等

  • 除去RandomAccessFile类外所有的流都继承于四个基本数据流抽象类InputSteam、OutputSteam、Reader、Writer

  • 不同的操作流对应的后缀均为四个抽象基类中的某一个

  • 不同处理流的使用方式都是标准操作:

    • 创建文件对象,创建相应的流
    • 处理流数据
    • 关闭流
    • 用try-catch-finally处理异常
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值