首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Java的IO流详解

Java的IO流详解

原创
作者头像
艾伦耶格尔
发布2025-08-07 17:56:01
发布2025-08-07 17:56:01
2990
举报
文章被收录于专栏:Java高级Java高级

一、IO流概述

在计算机编程中,IO流(Input/Output Stream) 是实现程序与外部设备(如文件、网络、控制台)之间数据传输的核心机制。

核心概念:

  • 流(Stream):数据的有序序列,像水流一样单向流动。
  • 输入流(Input):从数据源读取数据到程序。
  • 输出流(Output):将数据从程序写入目标设备。

Java 的 IO 操作主要位于 java.iojava.nio 包中。


二、IO流的分类

分类方式

类型

说明

按流向

输入流

InputStream, Reader

输出流

OutputStream, Writer

按数据单位

字节流

以字节为单位,处理任意类型数据

字符流

以字符为单位,专用于文本处理

选择建议:

  • 处理图片、音频、视频等二进制数据 → 使用字节流
  • 处理文本文件 → 使用字符流

三、字节流详解

3.1 字节输入流:InputStream

FileInputStream - 文件字节输入流
代码语言:java
复制
// 传统方式(需手动关闭)
FileInputStream fis = null;
try {
    fis = new FileInputStream("example.txt");
    int content;
    while ((content = fis.read()) != -1) {
        System.out.print((char) content);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

⚠️ read() 返回 int,-1 表示文件末尾。


3.2 字节输出流:OutputStream

FileOutputStream - 文件字节输出流
代码语言:java
复制
FileOutputStream fos = null;
try {
    fos = new FileOutputStream("output.txt");
    String str = "Hello, World!";
    byte[] bytes = str.getBytes("UTF-8"); // 推荐指定编码
    fos.write(bytes);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

💡 write(byte[]) 可一次性写入整个字节数组,效率更高。


四、字符流详解

4.1 字符输入流:Reader

FileReader - 文件字符输入流
代码语言:java
复制
FileReader fr = null;
try {
    fr = new FileReader("example.txt");
    int c;
    while ((c = fr.read()) != -1) {
        System.out.print((char) c);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fr != null) {
        try {
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

✅ 字符流自动处理编码转换,更适合文本读取。


4.2 字符输出流:Writer

FileWriter - 文件字符输出流
代码语言:java
复制
FileWriter fw = null;
try {
    fw = new FileWriter("output.txt");
    String str = "Hello, Character Stream!";
    fw.write(str); // 直接写入字符串
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fw != null) {
        try {
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

五、缓冲流:提升IO效率的关键

直接使用基础流频繁读写磁盘效率低下。缓冲流通过在内存中设置缓冲区,减少IO操作次数。

5.1 缓冲字节流

BufferedInputStream
代码语言:java
复制
try (BufferedInputStream bis = new BufferedInputStream(
         new FileInputStream("example.txt"))) {
    
    int content;
    while ((content = bis.read()) != -1) {
        System.out.print((char) content);
    }
} catch (IOException e) {
    e.printStackTrace();
}
BufferedOutputStream
代码语言:java
复制
try (BufferedOutputStream bos = new BufferedOutputStream(
         new FileOutputStream("output.txt"))) {
    
    String str = "Hello, Buffered Output Stream!";
    bos.write(str.getBytes());
} catch (IOException e) {
    e.printStackTrace();
}

✅ 使用 try-with-resources 自动关闭资源,避免内存泄漏。


5.2 缓冲字符流(最常用)

BufferedReader - 支持按行读取
代码语言:java
复制
try (BufferedReader br = new BufferedReader(
         new FileReader("example.txt"))) {
    
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

🚀 readLine() 是处理文本文件的利器!

BufferedWriter - 高效写入文本
代码语言:java
复制
try (BufferedWriter bw = new BufferedWriter(
         new FileWriter("output.txt"))) {
    
    bw.write("Hello, Buffered Writer!");
    bw.newLine(); // 跨平台换行
    bw.write("Second Line");
} catch (IOException e) {
    e.printStackTrace();
}

💡 newLine() 自动适配不同操作系统的换行符。


六、对象流:序列化与反序列化

用于将 Java 对象保存到文件或通过网络传输。

6.1 序列化:ObjectOutputStream

代码语言:java
复制
class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    int age;

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

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

// 写入对象
try (ObjectOutputStream oos = new ObjectOutputStream(
         new FileOutputStream("person.dat"))) {
    
    Person person = new Person("Alice", 25);
    oos.writeObject(person);
} catch (IOException e) {
    e.printStackTrace();
}

⚠️ 类必须实现 Serializable 接口。


6.2 反序列化:ObjectInputStream

代码语言:java
复制
try (ObjectInputStream ois = new ObjectInputStream(
         new FileInputStream("person.dat"))) {
    
    Person person = (Person) ois.readObject();
    System.out.println(person);
} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
}

🔐 注意安全风险:反序列化可能执行恶意代码。


七、文件操作辅助类

7.1 File 类(传统IO)

代码语言:java
复制
File file = new File("example.txt");
if (file.exists()) {
    System.out.println("文件存在");
    System.out.println("大小: " + file.length() + " bytes");
    System.out.println("是否是文件: " + file.isFile());
    System.out.println("是否是目录: " + file.isDirectory());
} else {
    System.out.println("文件不存在");
}

File 类功能有限,且部分方法已过时。


7.2 Files 类(NIO.2,推荐)

代码语言:java
复制
Path path = Paths.get("example.txt");

// 读取所有行
try {
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    lines.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

// 写入多行
List<String> content = Arrays.asList("Line 1", "Line 2");
try {
    Files.write(Paths.get("output.txt"), content, StandardCharsets.UTF_8);
} catch (IOException e) {
    e.printStackTrace();
}

优势:

  • 方法更简洁
  • 支持路径操作
  • 自动资源管理
  • 性能更好

八、最佳实践与总结

场景

推荐方案

文本文件读取

BufferedReader 或 Files.readAllLines()

文本文件写入

BufferedWriter 或 Files.write()

二进制文件处理

BufferedInputStream / BufferedOutputStream

对象持久化

ObjectInputStream / ObjectOutputStream

简单文件操作

Files 工具类

✅ 核心建议:

  1. 优先使用缓冲流,提升性能。
  2. 使用 try-with-resources,确保资源自动释放。
  3. 文本处理用字符流,避免乱码。
  4. 大文件处理:分块读取,避免内存溢出。
  5. 推荐使用 NIO.2 的 Files 替代传统 File

总结

Java IO 体系虽然复杂,但掌握以下核心即可应对大多数场景:

代码语言:tex
复制
字节流 → 二进制数据
   ↓
字符流 → 文本数据
   ↓
缓冲流 → 提升性能
   ↓
对象流 → 序列化
   ↓
NIO.2 → 现代化高效操作

理解这些组件的协作关系,你就能写出高效、健壮的文件处理代码!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、IO流概述
  • 二、IO流的分类
  • 三、字节流详解
    • 3.1 字节输入流:InputStream
      • FileInputStream - 文件字节输入流
    • 3.2 字节输出流:OutputStream
      • FileOutputStream - 文件字节输出流
  • 四、字符流详解
    • 4.1 字符输入流:Reader
      • FileReader - 文件字符输入流
    • 4.2 字符输出流:Writer
      • FileWriter - 文件字符输出流
  • 五、缓冲流:提升IO效率的关键
    • 5.1 缓冲字节流
      • BufferedInputStream
      • BufferedOutputStream
    • 5.2 缓冲字符流(最常用)
      • BufferedReader - 支持按行读取
      • BufferedWriter - 高效写入文本
  • 六、对象流:序列化与反序列化
    • 6.1 序列化:ObjectOutputStream
    • 6.2 反序列化:ObjectInputStream
  • 七、文件操作辅助类
    • 7.1 File 类(传统IO)
    • 7.2 Files 类(NIO.2,推荐)
  • 八、最佳实践与总结
    • ✅ 核心建议:
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档