java各种流的常见使用方法及示例

 更新时间:2026年03月03日 10:14:37   作者:tjh510623!  
在java中所有数据都是使用流读写的,流是一组有序的数据序列,将数据从一个地方带到另一个地方,这篇文章主要介绍了java各种流的常见使用方法及示例的相关资料,需要的朋友可以参考下

流在 Java I/O 操作中扮演着核心角色,主要用于处理数据序列(如文件、网络连接、内存缓冲区等)。它们主要分为两大类:字节流字符流

核心概念

  • 字节流: 以字节为单位进行读写操作 (8-bit),适用于所有类型的数据(图片、音频、视频、文本等)。基类是 InputStreamOutputStream
  • 字符流: 以字符为单位进行读写操作 (16-bit),专为处理文本数据设计,能正确处理字符编码(如 UTF-8, GBK)。基类是 ReaderWriter

常用流类及示例

1. 文件字节流 (FileInputStream / FileOutputStream)

  • 用途: 读写文件中的原始字节数据。
  • 示例: 复制文件
import java.io.*;

public class FileCopy {
    public static void main(String[] args) {
        try (InputStream in = new FileInputStream("source.jpg");
             OutputStream out = new FileOutputStream("copy.jpg")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            System.out.println("文件复制完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 缓冲字节流 (BufferedInputStream / BufferedOutputStream)

  • 用途: 包装其他字节流,提供缓冲区,减少物理 I/O 次数,显著提升性能。强烈推荐使用!
  • 示例: 高效读取文件
import java.io.*;

public class BufferedRead {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("data.bin");
             BufferedInputStream in = new BufferedInputStream(fis)) {
            int data;
            while ((data = in.read()) != -1) {
                // 处理每个字节 data
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 数据流 (DataInputStream / DataOutputStream)

  • 用途: 读写 Java 基本数据类型 (int, double, boolean, String 等) 的二进制表示。
  • 示例: 写入并读取基本数据类型
import java.io.*;

public class DataStreamDemo {
    public static void main(String[] args) {
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"))) {
            dos.writeInt(100);
            dos.writeDouble(3.14);
            dos.writeBoolean(true);
            dos.writeUTF("你好");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"))) {
            int i = dis.readInt();
            double d = dis.readDouble();
            boolean b = dis.readBoolean();
            String s = dis.readUTF();
            System.out.println(i + ", " + d + ", " + b + ", " + s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. 对象流 (ObjectInputStream / ObjectOutputStream)

  • 用途: 读写实现了 Serializable 接口的 Java 对象的序列化/反序列化。
  • 示例: 序列化对象到文件
import java.io.*;

class Person implements Serializable {
    private String name;
    private transient int age; // transient 修饰的字段不会被序列化

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // ... Getters, Setters, toString ...
}

public class ObjectStreamDemo {
    public static void main(String[] args) {
        Person person = new Person("张三", 30);
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
            oos.writeObject(person);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
            Person readPerson = (Person) ois.readObject();
            System.out.println(readPerson); // 注意 age 字段为默认值 0 (未序列化)
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

5. 文件字符流 (FileReader / FileWriter)

  • 用途: 读写文本文件内容,按字符处理。注意编码问题! 默认使用平台默认编码。
  • 示例: 读取文本文件
import java.io.*;

public class FileReadWrite {
    public static void main(String[] args) {
        try (Reader reader = new FileReader("input.txt");
             Writer writer = new FileWriter("output.txt")) {
            char[] buffer = new char[1024];
            int charsRead;
            while ((charsRead = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, charsRead);
            }
            System.out.println("文本文件复制完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6. 缓冲字符流 (BufferedReader / BufferedWriter)

  • 用途: 包装其他字符流,提供缓冲区和便捷方法(如 readLine() 读取整行文本)。提升文本处理效率。
  • 示例: 逐行读取文本文件
import java.io.*;

public class BufferedReaderDemo {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

7. 转换流 (InputStreamReader / OutputStreamWriter)

  • 用途: 桥梁作用! 将字节流转换为字符流,并可显式指定字符编码。解决乱码问题的关键。
  • 示例: 按指定编码读取文件
import java.io.*;

public class EncodingDemo {
    public static void main(String[] args) {
        try (InputStream fis = new FileInputStream("input_gbk.txt");
             // 将字节流 fis 转换为字符流,并指定编码为 GBK
             Reader isr = new InputStreamReader(fis, "GBK");
             BufferedReader br = new BufferedReader(isr)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line); // 正确显示 GBK 编码的中文
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

8. 打印流 (PrintStream / PrintWriter)

  • 用途: 提供方便的打印方法 (print, println, printf),自动将各种类型的数据转换为文本输出。System.out 就是一个 PrintStream
  • 示例: 格式化输出到文件
import java.io.*;

public class PrintWriterDemo {
    public static void main(String[] args) {
        try (PrintWriter pw = new PrintWriter(new FileWriter("log.txt"))) {
            pw.println("日志开始:");
            pw.printf("时间: %tT%n", System.currentTimeMillis());
            pw.println("操作: 用户登录");
            pw.println("日志结束.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

9. 管道流 (PipedInputStream / PipedOutputStream / PipedReader / PipedWriter)

  • 用途: 实现线程间的通信。一个线程通过 PipedOutputStream/PipedWriter 写入数据,另一个线程通过对应的 PipedInputStream/PipedReader 读取数据。必须连接使用!
  • 示例: 线程间通信
import java.io.*;

public class PipedStreamDemo {
    public static void main(String[] args) throws IOException {
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos); // 连接管道

        Thread writerThread = new Thread(() -> {
            try (DataOutputStream dos = new DataOutputStream(pos)) {
                dos.writeUTF("Hello from writer thread!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        Thread readerThread = new Thread(() -> {
            try (DataInputStream dis = new DataInputStream(pis)) {
                String message = dis.readUTF();
                System.out.println("Reader thread received: " + message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        writerThread.start();
        readerThread.start();
    }
}

总结与选择建议

流类型典型类主要用途特点/注意点
字节流FileInputStream, FileOutputStream原始字节数据读写基础文件操作
BufferedInputStream, BufferedOutputStream提高字节流效率强烈推荐包装使用
DataInputStream, DataOutputStream读写基本数据类型二进制格式
ObjectInputStream, ObjectOutputStream对象序列化/反序列化对象需实现 Serializable
PipedInputStream, PipedOutputStream线程间字节通信必须成对连接
字符流FileReader, FileWriter文本文件读写注意编码(默认平台编码)
BufferedReader, BufferedWriter提高字符流效率,支持readLine()推荐用于文本处理
InputStreamReader, OutputStreamWriter字节流->字符流转换,指定编码解决乱码的关键
PrintStream, PrintWriter格式化打印输出System.outPrintStream
PipedReader, PipedWriter线程间字符通信必须成对连接

选择原则:

  1. 数据类型: 处理二进制数据(图片、音频等)用字节流;处理文本数据优先考虑字符流
  2. 性能: 使用 BufferedXxx 包装流提高效率。
  3. 功能: 根据需求选择特定功能的流(如读写基本类型用 DataXxx,序列化用 ObjectXxx)。
  4. 编码: 处理文本时,务必关注编码。使用 InputStreamReader/OutputStreamWriter 明确指定编码。
  5. 资源管理: 使用 try-with-resources 语句确保流正确关闭,避免资源泄漏。

总结

到此这篇关于java各种流的常见使用方法及示例的文章就介绍到这了,更多相关java常用流类示例内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • IDEA修改idea.vmoptions后,IDEA无法打开的解决方案

    IDEA修改idea.vmoptions后,IDEA无法打开的解决方案

    文章介绍了在IDEA中因错误修改启动参数导致无法启动的问题,指出正确的修改文件位置应在破解插件目录下的idea.vmoptions,并分享了个人经验供参考
    2025-10-10
  • Java日期处理工具类DateUtils详解

    Java日期处理工具类DateUtils详解

    这篇文章主要为大家详细介绍了Java日期处理工具类DateUtils的相关代码,包含日期和时间常用操作,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12
  • IntelliJ IDEA 中必有得插件和配置

    IntelliJ IDEA 中必有得插件和配置

    这篇文章主要介绍了IntelliJ IDEA 中必有得插件和配置,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05
  • JAVA随机打乱数组顺序的方法

    JAVA随机打乱数组顺序的方法

    这篇文章主要介绍了JAVA随机打乱数组顺序的方法,包含了随机数的应用及数组的排序等操作,是Java操作数组的典型应用,需要的朋友可以参考下
    2014-11-11
  • SpringBoot3使用​自定义注解+Jackson实现接口数据脱敏的步骤

    SpringBoot3使用​自定义注解+Jackson实现接口数据脱敏的步骤

    本文介绍了一种以优雅的方式实现对接口返回的敏感数据,如手机号、邮箱、身份证等信息的脱敏处理,这种方法也是企业常用方法,话不多说我们一起来看一下吧
    2024-03-03
  • 详解Spring Boot Admin监控服务上下线邮件通知

    详解Spring Boot Admin监控服务上下线邮件通知

    本篇文章主要介绍了详解Spring Boot Admin监控服务上下线邮件通知,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • 如何解决Webservice第一次访问特别慢的问题

    如何解决Webservice第一次访问特别慢的问题

    这篇文章主要介绍了如何解决Webservice第一次访问特别慢的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • java 中HttpClient传输xml字符串实例详解

    java 中HttpClient传输xml字符串实例详解

    这篇文章主要介绍了java 中HttpClient传输xml字符串实例详解的相关资料,需要的朋友可以参考下
    2017-04-04
  • JAVA正则表达式的基本使用教程

    JAVA正则表达式的基本使用教程

    这篇文章主要给大家介绍了关于JAVA正则表达式的基本使用教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Java常用开源库汇总

    Java常用开源库汇总

    这篇文章主要介绍了Java常用开源库的相关资料,文中讲解非常细致,帮助大家更好的理解和学习Java,感兴趣的朋友可以了解下
    2020-07-07

最新评论