Java IO 流学习笔记

Java IO 流学习笔记

1 什么是流

内存与存储设备之间传输数据的通道。

2 流的分类

2.1 按方向

  • 输入流:将存储设备中的内容读取到内存中;
  • 输出流:将内存中的内容写入到存储设备中。

2.2 按单位

  • 字节流:以字节为单位,可以读取所有数据;
  • 字符流:以字符为单位,只能读取文本数据。

字节(Byte)是计量单位,表示数据量多少,是计算机信息技术用于计量存储容量的一种计量单位,通常情况下一字节等于八位。
字符(Character)计算机中使用的字母、数字、字和符号,比如'A'、'B'、'$'、'&'等。

2.3 按功能

  • 节点流:具有实际传输数据的读写功能;
  • 过滤流:在节点流的基础之上增强的功能。

3 字节流抽象类

  • InputStream
    这个抽象类是表示输入字节流的所有类的超类。
    需要定义InputStream子类的应用InputStream必须始终提供一种返回输入的下一个字节的方法。
  • OutputStream
    这个抽象类是表示字节输出流的所有类的超类。 输出流接收输出字节并将其发送到某个接收器。
    需要定义OutputStream子类的应用OutputStream必须至少提供一个写入一个字节输出的方法。

4.文件输入输出流

4.1 FileInputStream输入流

(1) read() 单字节读取

/**
     * 单字节读取
     * read(): 从该输入流读取下一个数据字节
     * @param filePath
     */
    public static void demo1(String filePath){
        try(FileInputStream fileInputStream = new FileInputStream(filePath)){
            int data;
            while ((data = fileInputStream.read()) != -1){
                System.out.print((char) data);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

(2)read(byte[] b) 一次读取多个字节

/**
     * 一次读取多个字节
     *
     * read(byte[] b):从该输入流读取最多 byte.length个字节的数据到字节数组。
     * @param filePath
     */
    public static void demo2(String filePath){
        try(FileInputStream fileInputStream = new FileInputStream(filePath)){
            byte[] buf = new byte[3]; // 大小为3的缓存区
            int count = 0;
            while((count = fileInputStream.read(buf)) != -1){
                System.out.println(new String(buf, 0, count));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

(3) read(byte[] b, int off, int len)

 /**
     *一次读取多个字节
     *
     * read(byte[] b, int off, int len)
     * 从该输入流读取最多 len字节的数据到字节数组。
     * @param filePath
     */
    public static void demo3(String filePath){
        try(FileInputStream fileInputStream = new FileInputStream(filePath)){
            byte[] buf = new byte[3]; // 大小为3的缓存区
            int count = 0;
            while((count = fileInputStream.read(buf,0,buf.length)) != -1){
                System.out.println(new String(buf, 0, count));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4.2 FileOutputStream文件输出流

public class FileOutputStreamDemo {
    public static void main(String[] args) {
        String filePath = "/Users/pandamig/IdeaProjects/Study/IOStudy/src/main/resources/ccc.txt";
        try(FileOutputStream out = new FileOutputStream(filePath)){
            out.write("hello word!".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4.3 文件输入输出流案例

public class FileCopyDemo {
    public static void main(String[] args) {
        // 1.创建流,文件输入流,文件输出流
        String orgPath = "/Users/pandamig/IdeaProjects/Study/IOStudy/src/main/resources/ccc.txt";
        String tarPath = "/Users/pandamig/IdeaProjects/Study/IOStudy/src/main/resources/ddd.txt";

        try (
                FileInputStream in = new FileInputStream(orgPath);
                FileOutputStream out = new FileOutputStream(tarPath);
        ) {
       // 2 边读边写
            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = in.read(buf)) != -1) {
                out.write(buf, 0, count);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5 字节缓冲流

缓冲流:BufferedInputStream/ BufferedOutputStream

  • 提高IO效率,减少访问磁盘次数
  • 数据存储在缓冲区中,flush是将缓冲区的内容写入文件中,也可以直接close

5.1 BufferedInputStream

public class BufferedInputStreamDemo {

    public static void main(String[] args) {
        String filePath = "/Users/pandamig/IdeaProjects/Study/IOStudy/src/main/resources/ccc.txt";
        try (
                FileInputStream fis = new FileInputStream(filePath);
                BufferedInputStream bis = new BufferedInputStream(fis)
        ) {
            // 2 读取
            int data = 0;
            while ((data = bis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5.2 BufferedOutputStream

public class BufferedOutputStreamDemo {
    public static void main(String[] args) {
        String tarPath = "/Users/pandamig/IdeaProjects/Study/IOStudy/src/main/resources/eee.txt";
        try (
                FileOutputStream fos = new FileOutputStream(tarPath);
                BufferedOutputStream bos = new BufferedOutputStream(fos)
        ) {
            // 写入文件
            for (int i = 0; i < 10; i++) {
                bos.write("hello".getBytes());// 写入8k缓冲区
                bos.flush(); // 刷新到硬盘
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6 对象流

ObjectOutputStream / ObjectInputStream

  • 增强了缓冲区功能
  • 增强了读写8种基本数据类型和字符串的功能
  • 增强了读写对象的功能
    readObject() 从流中读取一个对象
    writeObject(Object obj) 向流中写入一个对象
    使用流传输对象的过程称为序列化、反序列化

6.1 使用ObjectOutputStream实现对象的序列化

public class ObjectOutputStreamDemo {

    public static void main(String[] args) {
        // 1.创建对象流
        try (
                FileOutputStream fos = new FileOutputStream("/Users/pandamig/IdeaProjects/Study/IOStudy/src/main/resources/student.bin");
                ObjectOutputStream oos = new ObjectOutputStream(fos)
        ) {
            // 2.序列化
            Student student = new Student();
            student.setAge(14);
            student.setName("hello");

            oos.writeObject(student);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.2 使用ObjectInputStream实现对象的反序列化

public class ObjectInputStreamDemo {
    public static void main(String[] args) {
        try (
                FileInputStream fis = new FileInputStream("/Users/pandamig/IdeaProjects/Study/IOStudy/src/main/resources/student.bin");
                ObjectInputStream ois = new ObjectInputStream(fis);
        ) {
            Student stu = (Student) ois.readObject();
            System.out.println(stu.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

6.3 注意事项

  • 1.某个类要想序列化必须实现Serializable接口
  • 2.序列化类中对象属性要求实现Serializable接口
  • 3.序列化版本号ID,保证序列化的类和反序列化的类是同一个类
  • 4.使用transient修饰属性,这个属性就不能序列化
  • 5.静态属性不能序列化
  • 6.序列化多个对象,可以借助集合来实现
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,331评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,372评论 3 398
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,755评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,528评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,526评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,166评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,768评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,664评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,205评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,290评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,435评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,126评论 5 349
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,804评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,276评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,393评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,818评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,442评论 2 359

推荐阅读更多精彩内容

  • Java IO流 IO流概述 文件类(File) 在计算机中所有的数据都是以文件的格式存储的。 文件类是文件和目录...
    我爱铲屎阅读 228评论 0 2
  • 一、IO流整体结构图 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称...
    慕凌峰阅读 1,161评论 0 12
  • File File类概述和构造方法 File:它是文件和目录路径名的抽象表示 文件和目录是可以通过File封装成对...
    NobilityQAQ阅读 295评论 0 0
  • IO 流是有起点和终点的有序的字节序列 IO 流的分类 输入流和输出流程序从外面读数据就是输入流,程序把数据保存到...
    简书一哥们阅读 276评论 0 0
  • Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言。Java 技术具有卓越的通用性、高效性、平台移植性和...
    Java小辰阅读 624评论 0 2