← 返回首页

Java IO流详解

📂 java ⏱ 3 min 562 words

什么是IO流

Java IO(Input/Output)流是用于处理输入输出操作的机制。流是数据的有序序列,可以是字节流或字符流。

IO流分类

字节流

字节流用于处理二进制数据,是最基础的IO流。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteStreamDemo {
    public static void main(String[] args) {
        String sourceFile = "source.txt";
        String targetFile = "target.txt";

        try (FileOutputStream fos = new FileOutputStream(targetFile)) {
            String content = "Hello Java IO Stream";
            fos.write(content.getBytes());
            System.out.println("写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (FileInputStream fis = new FileInputStream(targetFile)) {
            int data;
            StringBuilder sb = new StringBuilder();
            while ((data = fis.read()) != -1) {
                sb.append((char) data);
            }
            System.out.println("读取内容: " + sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

字符流

字符流用于处理文本数据,支持字符编码转换。

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CharStreamDemo {
    public static void main(String[] args) {
        String fileName = "text.txt";

        try (FileWriter fw = new FileWriter(fileName)) {
            fw.write("这是一个测试文件\n");
            fw.write("第二行内容\n");
            fw.write("Java字符流示例");
            System.out.println("字符流写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (FileReader fr = new FileReader(fileName)) {
            char[] buffer = new char[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = fr.read(buffer)) != -1) {
                sb.append(buffer, 0, len);
            }
            System.out.println("读取内容:\n" + sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

缓冲流

缓冲流在内部维护缓冲区,减少IO操作次数,提高性能。

import java.io.*;

public class BufferedStreamDemo {
    public static void main(String[] args) {
        String source = "source.txt";
        String target = "target.txt";

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target))) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            System.out.println("缓冲流复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (BufferedReader reader = new BufferedReader(new FileReader("text.txt"));
             BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {

            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
            System.out.println("字符缓冲流复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

转换流

转换流用于字节流和字符流之间的转换。

import java.io.*;

public class InputStreamReaderDemo {
    public static void main(String[] args) {
        String fileName = "data.txt";

        try (OutputStreamWriter writer = new OutputStreamWriter(
                new FileOutputStream(fileName), "UTF-8")) {
            writer.write("中文内容转换流测试\n");
            writer.write("Hello InputStreamReader");
            System.out.println("写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (InputStreamReader reader = new InputStreamReader(
                new FileInputStream(fileName), "UTF-8")) {
            char[] buffer = new char[1024];
            int len;
            while ((len = reader.read(buffer)) != -1) {
                System.out.print(new String(buffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

对象流

对象流用于对象的序列化和反序列化。

import java.io.*;

public class ObjectOutputStreamDemo implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

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

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

    public static void main(String[] args) {
        String fileName = "user.ser";

        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(fileName))) {
            ObjectOutputStreamDemo user = new ObjectOutputStreamDemo("张三", 25);
            oos.writeObject(user);
            System.out.println("对象序列化成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(fileName))) {
            ObjectOutputStreamDemo user = (ObjectOutputStreamDemo) ois.readObject();
            System.out.println("反序列化对象: " + user);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

文件操作

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class FileOperationDemo {
    public static void main(String[] args) {
        File file = new File("test.txt");

        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("文件存在: " + file.exists());
        System.out.println("是否文件: " + file.isFile());
        System.out.println("是否目录: " + file.isDirectory());
        System.out.println("文件大小: " + file.length() + " bytes");

        Path path = Paths.get(".");
        try {
            List<Path> files = Files.list(path)
                .limit(10)
                .toList();
            files.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

IO流最佳实践

  1. 使用try-with-resources自动关闭流
  2. 选择合适的流类型
  3. 使用缓冲流提高性能
  4. 注意字符编码问题
  5. 合理设置缓冲区大小

总结

Java IO流提供了丰富的输入输出操作能力。掌握字节流、字符流、缓冲流的使用,能帮助你高效地处理各种IO操作需求。