Java使用字节流、缓冲流、转换流与对象流读写文件的示例代码

 更新时间:2026年05月27日 08:33:31   作者:连杰李  
这段文章详细介绍了Java中的流及其分类,涵盖了字节流、缓冲流和转换流等核心概念,文章还阐述了如何使用这些流进行文件读写操作,包括字节流、缓冲流、转换流和对象流的使用方法,需要的朋友可以参考下

一、Java 中有哪些流

二、Java 中流的分类

  • 节点流(从文件内容到流的输入输出)
    • 字节流 FileInputStream FileOutputStream
    • 字符流 FileReader FileWriter
  • 处理流(基于节点流的进一步封装)
    • 缓冲流 BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
    • 转换流 DataInputStream DataOutputStream
    • 对象流 ObjectInputStream ObjectOutputStream

三、Java 中流如何使用

  • 字节流
    • 可以读写文本、图片、音频、视频等各种类型的文件。
    • 比如 world、png、mp4 等。
  • 字符流
    • 只可以读写文本文件
    • 比如 txt、java、py、c 等。
    • 注意 world excel ppt 不属于文本文件。
  • 缓冲流
    • 作用:先把数据缓存到内存中,然后批量写入磁盘中,减少跟磁盘交互的次数,可以提高读写文件的效率。
    • 如果不使用缓冲流,读一次写一次跟磁盘交互一次,跟磁盘交互次数多,读写效率较低。
  • 转换流
    • 用于文件内容的编码和解码,文件内容中保存的是二进制数据,解码后,我们才可以看懂。
    • 解码,把二进制数据按照指定的字符集转换为字符。
    • 编码,把字符按照指定字符集编码为二进制数据。
  • 对象流
    • 用于把对象序列化为二进制数据,以便持久化到磁盘或使用网络传输。
    • 反序列化,把二进制数据反序列化为内存中的 Java 对象。

四、使用字节流读写文件

    public void copyFileWithFile(String srcPath, String destPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //1.
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //3. 读写过程
            int len;
            byte[] buffer = new byte[100];
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. 关闭资源
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

五、使用缓冲流读写文件

    public void copyFileWithBuffered(String srcPath, String destPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);

            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3. 读写过程
            int len;
            byte[] buffer = new byte[100];
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. 关闭资源(1. 需要先关闭缓冲流,再关闭文件流 2. 默认情况下,关闭外层流时,也会自动关闭内部的流)
            try {
                if(bos != null)
                    bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(bis != null)
                    bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //可以省略
//        fos.close();
//        fis.close();
        }

    }

六、字符流只能读写文本文件

    public void test() {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            isr = new InputStreamReader(new FileInputStream("康师傅的话.txt"),"gbk");

            osw = new OutputStreamWriter(new FileOutputStream("C:\\Users\\shkstart\\Desktop\\寄语.txt"),"utf-8");

            char[] cbuf = new char[1024];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf, 0, len);
                osw.flush();
            }
            System.out.println("文件复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null)
                    isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (osw != null)
                    osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

七、使用转换流进行解码编码

使用 UTF8 解码文件得到文件内容后使用 GBK 编码文件输出到新的文件中

    public void test4() {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            //1. 造文件
            File file1 = new File("dbcp_gbk.txt");
            File file2 = new File("dbcp_gbk_to_utf8.txt");

            //2. 造流
            FileInputStream fis = new FileInputStream(file1);
            //参数2对应的是解码集,必须与dbcp_gbk.txt的编码集一致。
            isr = new InputStreamReader(fis,"GBK");


            FileOutputStream fos = new FileOutputStream(file2);
            //参数2指明内存中的字符存储到文件中的字节过程中使用的编码集。
            osw = new OutputStreamWriter(fos,"utf8");

            //3. 读写过程
            char[] cBuffer = new char[1024];
            int len;
            while((len = isr.read(cBuffer)) != -1){
                osw.write(cBuffer,0,len);
            }

            System.out.println("操作完成");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //4. 关闭资源
            try {
                if(osw != null)
                    osw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if(isr != null)
                    isr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

八、使用对象流序列化反序列化

person 对象

package com.atguigu05.objectstream;
import java.io.Serializable;

public class Person implements Serializable { //Serializable:属于一个标识接口
    String name;
    int age;

    int id;

    Account acct;

    static final long serialVersionUID = 422334254234L;

    public Person() {
    }

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

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

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", id=" + id +
                ", acct=" + acct +
                '}';
    }
}

class Account implements Serializable{
    double balance;

    static final long serialVersionUID = 422234L;

    public Account(double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "balance=" + balance +
                '}';
    }
}

序列化 person 对象

    public void test3(){
        ObjectOutputStream oos = null;
        try {
            File file = new File("object1.dat");
            oos = new ObjectOutputStream(new FileOutputStream(file));

            //2.写出数据即为序列化的过程
            Person p1 = new Person("Tom",12);
            oos.writeObject(p1);
            oos.flush();

            Person p2 = new Person("Jerry",23,1001,new Account(2000));
            oos.writeObject(p2);
            oos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(oos != null)
                    oos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

反序列化 person 对象

    public void test4() {
        ObjectInputStream ois = null;
        try {
            File file = new File("object1.dat");
            ois = new ObjectInputStream(new FileInputStream(file));

            //2. 读取文件中的对象(或反序列化的过程)
            Person person = (Person) ois.readObject();
            System.out.println(person);

            Person person1 = (Person) ois.readObject();
            System.out.println(person1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(ois != null)
                    ois.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

以上就是Java使用字节流、缓冲流、转换流与对象流读写文件的示例代码的详细内容,更多关于Java读写文件的资料请关注脚本之家其它相关文章!

相关文章

  • SpringBoot整合XXLJob的实现示例

    SpringBoot整合XXLJob的实现示例

    XXLJob是大众点评开源的分布式任务调度平台,支持Cron、固定间隔等触发方式,本文主要介绍了SpringBoot整合XXLJob的实现示例,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-09-09
  • java实现浮点数转人民币的小例子

    java实现浮点数转人民币的小例子

    java实现浮点数转人民币的小例子,需要的朋友可以参考一下
    2013-03-03
  • spring boot对敏感信息进行加解密的项目实现

    spring boot对敏感信息进行加解密的项目实现

    本文主要介绍了spring boot对敏感信息进行加解密的项目实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Spring整合Redis完整实例代码

    Spring整合Redis完整实例代码

    这篇文章主要介绍了Spring整合Redis完整实例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-04-04
  • jmeter断言的三种实现方式

    jmeter断言的三种实现方式

    在使用Jmeter进行性能测试或者接口自动化测试工作中,经常会用到的一个功能,就是断言,本文主要介绍了jmeter断言的三种实现方式,
    2024-01-01
  • IDEA连接MySQL数据库的4种方法图文教程

    IDEA连接MySQL数据库的4种方法图文教程

    IDEA是一种流行的Java开发工具,可以方便地连接MySQL,这篇文章主要给大家介绍了关于IDEA连接MySQL数据库的4种方法,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2023-12-12
  • spring学习之util:properties的使用

    spring学习之util:properties的使用

    这篇文章主要介绍了spring学习之util:properties的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • Spring Boot Actuator未授权访问漏洞的问题解决

    Spring Boot Actuator未授权访问漏洞的问题解决

    Spring Boot Actuator 端点的未授权访问漏洞是一个安全性问题,可能会导致未经授权的用户访问敏感的应用程序信息,本文就来介绍一下解决方法,感兴趣的可以了解一下
    2023-09-09
  • 如何计算Java对象占用了多少空间?

    如何计算Java对象占用了多少空间?

    在Java中没有sizeof运算符,所以没办法知道一个对象到底占用了多大的空间,但是在分配对象的时候会有一些基本的规则,我们根据这些规则大致能判断出来对象大小,需要的朋友可以参考下
    2016-01-01
  • 10个Java解决内存溢出OOM的方法详解

    10个Java解决内存溢出OOM的方法详解

    在Java开发过程中,有效的内存管理是保证应用程序稳定性和性能的关键,不正确的内存使用可能导致内存泄露甚至是致命的OutOfMemoryError(OOM),下面我们就来学习一下有哪些解决办法吧
    2024-01-01

最新评论