Java 学习系列(6):Java I/O 详解

Java 学习系列(6):Java I/O 详解

1. Java I/O 概述

Java I/O(输入/输出)是 Java 语言中处理数据流的重要组成部分,主要用于读取和写入数据。

  • java.io 包提供了同步、阻塞式 I/O。
  • java.nio 包提供了非阻塞式 I/O(NIO),提高性能。

2. Java I/O 流的分类

Java I/O 按照数据处理方式可以分为:

  1. 按数据类型

    • 字节流(InputStream / OutputStream):处理二进制数据。
    • 字符流(Reader / Writer):处理文本数据。
  2. 按流向

    • 输入流(InputStream / Reader):用于读取数据。
    • 输出流(OutputStream / Writer):用于写入数据。

3. 文件 I/O 操作

3.1 使用 FileInputStreamFileOutputStream

import java.io.*;

public class FileIOExample {
    public static void main(String[] args) throws IOException {
        // 写入文件
        try (FileOutputStream fos = new FileOutputStream("test.txt")) {
            fos.write("Hello, Java I/O!".getBytes());
        }
        
        // 读取文件
        try (FileInputStream fis = new FileInputStream("test.txt")) {
            int ch;
            while ((ch = fis.read()) != -1) {
                System.out.print((char) ch);
            }
        }
    }
}

3.2 使用 BufferedReaderBufferedWriter

import java.io.*;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        // 写入文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"))) {
            writer.write("Hello, Buffered I/O!");
        }
        
        // 读取文件
        try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

4. java.nio 介绍

NIO(New I/O)是 Java 1.4 引入的,提供了基于 缓冲区(Buffer)通道(Channel) 的非阻塞 I/O 机制。

4.1 使用 FileChannel 进行文件读写

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class NIOFileExample {
    public static void main(String[] args) throws IOException {
        // 写入文件
        try (FileChannel channel = new FileOutputStream("test_nio.txt").getChannel()) {
            ByteBuffer buffer = ByteBuffer.wrap("Hello, NIO!".getBytes());
            channel.write(buffer);
        }
        
        // 读取文件
        try (FileChannel channel = new FileInputStream("test_nio.txt").getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            channel.read(buffer);
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }
        }
    }
}

5. 对象序列化

Java 提供 ObjectOutputStreamObjectInputStream 来实现对象的序列化和反序列化。

import java.io.*;

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;
    }
}

public class SerializationExample {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 序列化
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            oos.writeObject(new Person("Alice", 25));
        }
        
        // 反序列化
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
            Person p = (Person) ois.readObject();
            System.out.println("姓名: " + p.name + ", 年龄: " + p.age);
        }
    }
}

6. 资源自动关闭(try-with-resources

Java 7 引入 try-with-resources 语法,可以自动关闭 Closeable 资源,避免手动 close()

try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
    System.out.println(br.readLine());
} catch (IOException e) {
    e.printStackTrace();
}

7. 总结

  • Java I/O 主要包括 字节流InputStream / OutputStream)和 字符流Reader / Writer)。
  • 使用 缓冲流BufferedReader / BufferedWriter)提高效率。
  • NIO 提供了基于 BufferChannel 的高效非阻塞 I/O。
  • 对象流ObjectOutputStream / ObjectInputStream)支持对象序列化。
  • try-with-resources 语法自动管理资源。

下一期:《Java 学习系列(7):Java 反射机制详解》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值