Java-I/O流

在这里插入图片描述

IO流的分类方式:

一种方式是按照流的方向进行分类:

  • 往内存中去,叫做输入(Input),或者叫做读(Read)
  • 从内存中出来,叫做输出(Output),或者叫做写(Write)

另一种方式是按照读取数据方式不同进行分类:

  • 有的流是按照字节的方式读取教据,一次读取1个字节byte,等同于一次读取8个二进制位,这种流是方能的,什么类型的文件都可以读取。包括:文本文件(xxx.txt),图片,声音文件,视频。
  • 有的流是按照字符的方式读取数据的,一次读取一个字符,这种流是为了方便读取普通文本文件而存在的,这种流不能读取:图片、声音、视频等文件。只能读取纯文本文件(xxx.txt),连word文件都无法读取。

字符流和字节流的不同:

“a我”(在windows操作系统里面一个汉字占两个字节,a字母占一个字节,在Java中’a’字符(也就是char类型是两个字节的)占两个字节)
采用字符流:第一次读’a’字符,第二次读’我’字符
采用字节流:第一次读第一个字节(也就是’a’字符,这个文件不关Java的事,文件在操作系统中,就只是占用一个字节),第二次读第二个字节(我字符的一半),第三次读第三个字节(我字符的另一半)


Java I/O流有四大顶级抽象类

  • java.io.Inputstream (字节输入流)

  • java.io.outputstream (字节输出流)

  • java.io.Reader (字符输入流)

  • java.io.Writer (字符输出流)

注意:在Java中只要"类名"以stream结尾的都是字节流。以"Reader/Writer"结尾的都是字符流(看结尾)。
所有的流都实现了java.io.Closeable接口,都是可关闭的,都有close()方法。用完流一定要关闭。
所有的输出流都实现了java.io.Flushable接口,都是可刷新的,都有flush()方法。输出流在最终输出之后,一定要记得flush()刷新一下。这个刷新表示将流通道当中剩余未输出的数据强行输出完,刷新的作用就是清空管道。

我们要掌握的流有16个

文件流:

  • java.io.FileInputStream
  • java.io.FileOutputStream
  • java.io.FileReader
  • java.io.FileWriter

转换流:(将字节流转换成字符流)

  • java.io.InputStreamReader
  • java.io.OutputStreamWriter

缓冲流:

  • java.io.BufferedReader
  • java.io.BufferedWriter
  • java.io.BufferedInputStream
  • java.io.BufferedOutputStream

数据流:

  • java.io.DataInputStream
  • java.io.DataOutputStream

标准输出流:

  • java.io.PrintWriter
  • java.io.PrintStream

对象流:

  • java.io.ObjectInputStream
  • java.io.ObjectOutputStream

FileInputStream

package IO;

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

// 文件字节输入流
public class FileInputStreamTest {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null; // 提升fileInputStream变量作用域方便后面finally语句的文件流关闭
        try {
            /*
            第一个 \ 是转义符,文件路径表示不能单独出现,会被识别成转义符而不是路径符号
            单独用的话可以用 /
            */
            fileInputStream = new FileInputStream("D:/springboot-study/Demo01/src/IO/pang.txt");
            while (true){
                // read():从这个输入流读取一个字节的数据。如果没有数据读取就返回-1
                int readData = fileInputStream.read();
                if(readData == -1){
                    break;
                }
                System.out.println(readData);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream != null) {
                try {
                    /*防止空指针异常,关闭流的前提是:流不是空,流是null的时候没必要关闭。因为流没有被初始化,
                    也就是fileInputStream = new FileInputStream("D:/springboot-study/Demo01/src/IO/pang.txt")异常的情况下不用关闭,
                    不然会报空指针异常
                    */
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
package IO;

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

/**
* int read( byte[] b)
*一次最多读取b.Length个字节。
*减少硬盘和内存的交互,提高程序的执行效率,往byte[]数组当中读。
*/
public class FileInputStreamTest01 {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("\\pang");

            byte[] bytes = new byte[9];
            int readCount = 0;
            // read(byte[] b )往数组里面传字符串,返回值是读到的字符个数
            while ((readCount = fileInputStream.read(bytes)) != -1){
                // 将byte数组转化为字符串,读到多少个转化多少个
                System.out.println(new String(bytes, 0, readCount));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

FileInputStream常用方法:

package IO;

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

public class FileInputStreamTest01 {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("src\\IO\\pang.txt");

            byte[] bytes = new byte[fileInputStream.available()];// available()返回未读的字节数,不适用于大文件,初始化后第一次就是计算总字节数
                fileInputStream.read(bytes);// 读一次就能读完
                System.out.println(new String(bytes));
                
			/*// skip(3) 跳过三个字节不读
            fileInputStream.skip(3);
            System.out.println(fileInputStream.read());*/

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

FileOutputStream

package IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamTest {
    public static void main(String[] args) {
        FileOutputStream fileOutputStream = null;
        try {
            // append参数置true,写操作不会清空文件从头写,而是在文件末尾以追加等的方式进行写
            fileOutputStream = new FileOutputStream("src/IO/lol.txt",true);
            byte[] bytes = {33,11,99};
            
            // off:起始位置,写的长度
            fileOutputStream.write(bytes,0,3);

            // 写完后要刷新
            fileOutputStream.flush();

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

万能的文件复制代码

package IO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 把pang.txt内容复制到lol.txt中
* */
public class CopyTest {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;


        try {
            fileOutputStream = new FileOutputStream("src/IO/lol.txt");
            fileInputStream = new FileInputStream("src/IO/pang.txt");

            byte[] bytes = new byte[1024 * 1024]; // 1MB
            int readCount = 0;
            while ((readCount = fileInputStream.read(bytes)) != -1){
                fileOutputStream.write(bytes,0,readCount);
            }
            fileOutputStream.flush();
            System.out.println("复制成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 要分开处理,一起try因为第一次异常,代码终止,第二个就不会执行关闭操作
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

转换流

package IO;

import java.io.*;

/*
* 转换流的用法
* */
public class InputStreamReaderTest {
    public static void main(String[] args) {
        try {
            // 看源码发现BufferedReader()的构造方法需要一个Reader类对象,这时候要转化流把InputStream转化为Reader
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("src/IO/lol.txt")));
            String s = null;
            while ((s = br.readLine()) != null){
                System.out.println(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

对象流

序列化 : (Serialize)java对象存储到文件中。将java对象的状态保存下来的过程。
反序列化: (DeSerialize)将硬盘上的数据重新恢复到内存当中,恢复成java对象。

package IO;

import java.io.Serializable;
// java虚拟机先通过类名判别,类名一样就通过序列号判别是不是同一个类
// 要实现Serializable接口才能参加序列化
public class People implements Serializable {

    /*
    过了很久,People这个类源代码改动了。
    源代码改动之后,需要重新编译,编译之后生成了全新的字节码文件。
    并且class文件再次运行的时候,java虚拟机生成的序列化版本号也会发生相应的改变。反序列化就会失败
    Java虚拟机看到erializable接口之后,会自动生成一个序列化版本号。
    这里没有手动写出来,java虚拟机会默认提供这个序列化版本号。
    建议将序列化版本号手动的写出来。不建议自动生成
    */

    private static final long serialVersionUID = 21654135L;


    private transient String name; // transient 游离的,这个属性不参加序列化,反序列化的时候得到的name为null
    private String id;

    public String getName() {
        return name;
    }

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

    public String getId() {
        return id;
    }

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


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

    public People(String name, String id) {
        this.name = name;
        this.id = id;
    }
}
package IO;

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

public class ObjectOutputStreamTest {
    public static void main(String[] args) throws IOException {
        People people = new People();
        //序列化
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/IO/jian.txt"));
        //序列化对象
        oos.writeObject(people);

        // 刷新
        oos.flush();
        // 关闭
        oos.close();

    }
}
package IO;

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

public class ObjectInputStreamTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //反序列化
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/IO/jian.txt"));
        Object object = ois.readObject();
        System.out.println(object.toString());
        ois.close();
    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值