Java IO 与 NIO 实战

读文件、写文件、复制文件——Java IO 是基本功。本文从字节流、字符流到 NIO 文件通道,用实战例子讲清 Java 文件操作的核心用法。

Java IO 配图:蓝色渐变背景上流动数据流如并行河流在堆叠存储层之间,扁平科技插画
Java IO:文件读写的基础工具链

一、IO 流的分类

分类维度类型说明
数据单位字节流InputStream / OutputStream,处理二进制
数据单位字符流Reader / Writer,处理文本
方向输入流读数据
方向输出流写数据
功能节点流直接连数据源
功能处理流包装节点流,加缓冲等功能

二、读文本文件

import java.io.*;
import java.nio.file.*;
import java.util.List;

// 方式一:Files.readAllLines(最简单,小文件)
List lines = Files.readAllLines(Paths.get("test.txt"));
for (String line : lines) {
    System.out.println(line);
}

// 方式二:BufferedReader(大文件逐行读)
try (BufferedReader br = Files.newBufferedReader(Paths.get("big.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
try-with-resources:Java 7+ 的 try-with-resources 自动关闭流,不用手写 finally。实现 AutoCloseable 接口的流都能用。

三、写文本文件

import java.io.*;
import java.nio.file.*;
import java.util.*;

// 方式一:Files.write(简单写)
List content = Arrays.asList("第一行", "第二行", "第三行");
Files.write(Paths.get("output.txt"), content);

// 方式二:BufferedWriter(追加写)
try (BufferedWriter bw = Files.newBufferedWriter(
        Paths.get("log.txt"), StandardOpenOption.APPEND)) {
    bw.write("新的日志行");
    bw.newLine();
} catch (IOException e) {
    e.printStackTrace();
}

四、复制文件

import java.nio.file.*;

// NIO 一行复制
Files.copy(Paths.get("source.txt"), Paths.get("target.txt"),
    StandardCopyOption.REPLACE_EXISTING);

// 大文件用流复制
try (InputStream in = Files.newInputStream(Paths.get("large.bin"));
     OutputStream out = Files.newOutputStream(Paths.get("copy.bin"))) {
    byte[] buffer = new byte[8192];
    int len;
    while ((len = in.read(buffer)) != -1) {
        out.write(buffer, 0, len);
    }
}

五、NIO FileChannel

import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;

// NIO 通道 + 缓冲区
RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
FileChannel channel = file.getChannel();

ByteBuffer buffer = ByteBuffer.allocate(1024);

// 读
channel.read(buffer);
buffer.flip();
while (buffer.hasRemaining()) {
    System.out.print((char) buffer.get());
}
buffer.clear();

// 写
buffer.put("Hello NIO".getBytes());
buffer.flip();
channel.write(buffer);

channel.close();
file.close();

六、文件操作工具

import java.nio.file.*;

Path path = Paths.get("test.txt");

// 判断文件是否存在
boolean exists = Files.exists(path);

// 创建目录
Files.createDirectories(Paths.get("a/b/c"));

// 删除文件
Files.deleteIfExists(path);

// 遍历目录
try (DirectoryStream stream = Files.newDirectoryStream(Paths.get("."))) {
    for (Path p : stream) {
        System.out.println(p.getFileName());
    }
}

// 获取文件大小
long size = Files.size(path);

七、总结

日常文件操作优先用 java.nio.file.Files 工具类,一行代码搞定读写复制。大文件用 BufferedReader 逐行读、BufferedWriter 逐行写。NIO 的 FileChannel 适合高性能文件操作。记住 try-with-resources 自动关闭流,不用手写 finally。