温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java nio文件操作怎么写

发布时间:2026-10-13 13:41:22 来源:亿速云 阅读:96 作者:小樊 栏目:编程语言

下面给你一份Java NIO 文件操作的常用写法总结,基于 java.nio.file 包(JDK 7+),比传统 IO 更简洁、效率更高。


一、核心类说明

  • Paths:创建 Path
  • Path:文件路径
  • Files:文件操作工具类
  • FileSystem / FileChannel:底层通道(高级用法)

二、常见文件操作示例

1️⃣ 创建文件 / 目录

import java.nio.file.*;

public class NioDemo {
    public static void main(String[] args) throws Exception {
        Path dir = Paths.get("testDir");
        Path file = Paths.get("testDir/test.txt");

        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
        }

        if (!Files.exists(file)) {
            Files.createFile(file);
        }
    }
}

2️⃣ 写入文件

覆盖写入

Path path = Paths.get("test.txt");
Files.write(path, "Hello NIO".getBytes());

追加写入

Files.write(
    path,
    "append content".getBytes(),
    StandardOpenOption.CREATE,
    StandardOpenOption.APPEND
);

3️⃣ 读取文件

读全部内容(小文件)

byte[] data = Files.readAllBytes(path);
String content = new String(data);

按行读取

List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);

流式读取(大文件)

try (Stream<String> stream = Files.lines(path)) {
    stream.forEach(System.out::println);
}

4️⃣ 复制 / 移动 / 删除

Path src = Paths.get("a.txt");
Path dest = Paths.get("b.txt");

// 复制
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);

// 移动
Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING);

// 删除
Files.deleteIfExists(dest);

5️⃣ 遍历目录

Path root = Paths.get("testDir");

try (DirectoryStream<Path> stream = Files.newDirectoryStream(root)) {
    for (Path p : stream) {
        System.out.println(p.getFileName());
    }
}

递归遍历

Files.walk(root).forEach(System.out::println);

6️⃣ 文件属性

boolean isDir = Files.isDirectory(path);
long size = Files.size(path);

三、使用 FileChannel(高效 NIO)

try (FileChannel in = FileChannel.open(src, StandardOpenOption.READ);
     FileChannel out = FileChannel.open(dest,
             StandardOpenOption.CREATE,
             StandardOpenOption.WRITE)) {
    in.transferTo(0, in.size(), out);
}

四、常见注意点

✅ NIO 更适合:

  • 大文件
  • 高并发
  • 流式处理

⚠️ 小文件直接用 Files.readAllBytes 最简单


如果你有具体场景(比如:大文件读写、断点续传、 monitor 目录变化、网络 + NIO),我可以给你更针对性的代码。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手