0Pricing
Java Academy · 课时

Files 工具:读取、写入、复制与移动

使用 Files.readString、writeString、copy、move 和 delete 执行常见文件操作

Files 工具:读取、写入、复制与移动 是 CoddyKit 上的免费 Java Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Java Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Java Academy 课程共包含 4 节课。

Files 类

java.nio.file.Files 类提供用于读取、写入、复制、移动和查询文件的静态工具方法。它取代了冗长的 FileInputStream/FileOutputStream 样板代码。

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

Path file = Path.of("example.txt");
// All Files methods throw IOException — handle or propagate

读取文件

读取文件全部内容的现代方法:

Path path = Path.of("notes.txt");

// Read as a single String (Java 11+)
String content = Files.readString(path);
System.out.println(content);

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

// Read as byte array
byte[] bytes = Files.readAllBytes(path);

写入文件

一次调用即可将 String 或多行集合写入文件:

Path out = Path.of("output.txt");

// Write a String (overwrites by default)
Files.writeString(out, "Hello, NIO.2!");

// Write with StandardOpenOption.APPEND
Files.writeString(out, "\nAppended line", StandardOpenOption.APPEND);

// Write lines
List<String> lines = List.of("line1", "line2", "line3");
Files.write(out, lines);

检查文件属性

无需打开文件即可查询文件元数据:

Path path = Path.of("data.txt");

System.out.println(Files.exists(path));       // true/false
System.out.println(Files.isRegularFile(path)); // true if not dir
System.out.println(Files.isDirectory(path));   // true if dir
System.out.println(Files.isReadable(path));    // readable?
System.out.println(Files.size(path));          // bytes
System.out.println(Files.getLastModifiedTime(path));

复制文件

Files.copy(source, target) 会复制文件。使用 StandardCopyOption 控制行为:

Path src = Path.of("original.txt");
Path dst = Path.of("backup.txt");

// Throws if destination exists (default)
Files.copy(src, dst);

// Overwrite if exists:
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

// Copy preserving file timestamps:
Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES);

移动和重命名文件

Files.move() 会移动或重命名文件。使用 ATOMIC_MOVE 可以执行原子移动:

Path from = Path.of("temp.txt");
Path to   = Path.of("archive/report_2024.txt");

Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);

// Rename in same directory:
Path renamed = from.resolveSibling("new_name.txt");
Files.move(from, renamed, StandardCopyOption.REPLACE_EXISTING);

删除文件

有两种删除方法——一种在找不到目标时抛出异常,另一种不会:

Path file = Path.of("temp.txt");

// Throws NoSuchFileException if file doesn't exist:
Files.delete(file);

// Returns false if file didn't exist (no exception):
boolean deleted = Files.deleteIfExists(file);
System.out.println("Deleted: " + deleted);

创建目录

创建目录,包括所有中间目录:

Path dir = Path.of("output/reports/2024");

// Creates all missing intermediate directories:
Files.createDirectories(dir);

// Creates a single directory (fails if parent missing):
Files.createDirectory(Path.of("output/reports/2025"));

临时文件和目录

安全地创建临时文件——JVM 可以清理这些文件:

// Temp file in default temp directory
Path tmp = Files.createTempFile("prefix_", ".txt");
Files.writeString(tmp, "temp data");
System.out.println(tmp); // something like /tmp/prefix_12345.txt

// Temp directory
Path tmpDir = Files.createTempDirectory("work_");
System.out.println(tmpDir);

使用 Files.lines 流式读取行

Files.lines() 返回惰性的 Stream<String>。对于大型文件,它比 readAllLines 更好,因为不会将全部内容加载到内存中:

try (var stream = Files.lines(Path.of("large.log"))) {
    long errorCount = stream
        .filter(l -> l.contains("ERROR"))
        .count();
    System.out.println("Errors: " + errorCount);
} // stream (and underlying reader) closed automatically

读取类路径资源

将 getClass().getResourceAsStream() 与 NIO 复制结合使用来加载资源:

try (var in = getClass().getResourceAsStream("/config.json")) {
    Path tmp = Files.createTempFile("config", ".json");
    Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
    String json = Files.readString(tmp);
    System.out.println(json);
}

快速检查

如果不想同时将大型日志文件的所有行加载到内存中,应使用哪个方法读取它?

回顾:Files 工具类

要点:

  • Files.readString/readAllLines/readAllBytes——读取整个文件
  • Files.writeString/write——写入字符串或多行内容
  • Files.copy/move 与 StandardCopyOption——复制、重命名或移动
  • Files.delete/deleteIfExists——安全删除
  • Files.lines——用于大型文件的惰性流(请使用 try-with-resources)

常见问题解答

「Files 工具:读取、写入、复制与移动」课时是免费的吗?

是的 — 「Files 工具:读取、写入、复制与移动」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Java Academy 课程的其余内容,请升级到 CoddyKit PRO。 Java Academy 课程共包含 4 节课。

「Files 工具:读取、写入、复制与移动」这节课中我会学到什么?

使用 Files.readString、writeString、copy、move 和 delete 执行常见文件操作 你通过在浏览器中直接运行的动手代码来练习 Java Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Java Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Java Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「Files 工具:读取、写入、复制与移动」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Java Academy 课中编写并运行代码吗?

能。每节 Java Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Path:表示文件位置
  2. Files 工具:读取、写入、复制与移动
  3. 使用 Files.walk 遍历目录树
  4. WatchService:监控文件变化
← 返回 Java Academy