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读写文件的资料请关注脚本之家其它相关文章!

相关文章

  • Spring事务隔离级别简介及实例解析

    Spring事务隔离级别简介及实例解析

    这篇文章主要介绍了Spring事务隔离级别简介及实例解析,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-02-02
  • java如何自定义注解

    java如何自定义注解

    这篇文章主要介绍了java如何自定义注解问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • Quartz集群原理以及配置应用的方法详解

    Quartz集群原理以及配置应用的方法详解

    Quartz是Java领域最著名的开源任务调度工具。Quartz提供了极为广泛的特性如持久化任务,集群和分布式任务等,下面这篇文章主要给大家介绍了关于Quartz集群原理以及配置应用的相关资料,需要的朋友可以参考下
    2018-05-05
  • SSH框架网上商城项目第6战之基于DataGrid的数据显示

    SSH框架网上商城项目第6战之基于DataGrid的数据显示

    SSH框架网上商城项目第6战之基于DataGrid的数据显示,提供了丰富的选择、排序、分组和编辑数据的功能支持,感兴趣的小伙伴们可以参考一下
    2016-05-05
  • java实现注册登录系统

    java实现注册登录系统

    这篇文章主要为大家详细介绍了java实现注册登录系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • 一问详解SpringBoot配置文件优先级

    一问详解SpringBoot配置文件优先级

    在SpringBoot项目当中,我们要想配置一个属性,可以通过这三种方式当中的任意一种来配置都可以,那么优先级怎么算,本文主要介绍了一问详解SpringBoot配置文件优先级,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Java基础之创建虚拟机对象的过程详细总结

    Java基础之创建虚拟机对象的过程详细总结

    本文基于虚拟机HotSpot和常用的内存区域Java堆深入对象分配、布局和访问的全过程,文中有非常详细的图文解说,对正在学习java的小伙伴们很有帮助,需要的朋友可以参考下
    2021-05-05
  • maven国内镜像配置的方法步骤

    maven国内镜像配置的方法步骤

    这篇文章主要介绍了maven国内镜像配置的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • Spring Bean初始化和销毁的三种方式

    Spring Bean初始化和销毁的三种方式

    这篇文章介绍了Spring框架中Bean的初始化和销毁的几种方式,包括实现InitializingBean接口、使用@PostConstruct注解、自定义init方法以及实现DisposableBean接口、使用@PreDestroy注解和自定义销毁方法,需要的朋友可以参考下
    2025-11-11
  • SpringBoot实现异步的八种方法

    SpringBoot实现异步的八种方法

    Spring Boot 的异步处理主要是通过非阻塞I/O和回调机制来实现的,目的是提高应用的并发性能,它支持多种方式来创建异步任务,本文给大家介绍了SpringBoot实现异步的八种方法,需要的朋友可以参考下
    2024-07-07

最新评论