文件处理是 Java 应用程序中最常见、最实用的功能之一,无论是读取配置文件、处理日志、批量处理 CSV,还是备份、压缩文件,都离不开对文件的高效操作。
本篇文章将系统讲解 Java 文件操作的各个方面,包括文件读取、写入、复制、删除、压缩等,并提供实际代码示例。
File
类检查文件属性java复制编辑import java.io.File;
public class FileCheck {
public static void main(String[] args) {
File file = new File("example.txt");
System.out.println("文件是否存在: " + file.exists());
System.out.println("是否是文件: " + file.isFile());
System.out.println("是否是目录: " + file.isDirectory());
System.out.println("文件大小(字节): " + file.length());
System.out.println("绝对路径: " + file.getAbsolutePath());
}
}
🖼️ 图示(结构图):文件属性检测流程图
java复制编辑import java.io.*;
import java.nio.file.*;
public class FileReaderExample {
public static void main(String[] args) throws IOException {
Path path = Paths.get("data.txt");
Files.lines(path).forEach(System.out::println);
}
}
java复制编辑Files.write(Paths.get("output.txt"),
"写入内容".getBytes(),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
java复制编辑Path src = Paths.get("source.txt");
Path dest = Paths.get("copy.txt");
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
java复制编辑Files.deleteIfExists(Paths.get("copy.txt"));
需使用递归或 Files.walk()
:
java复制编辑Files.walk(Paths.get("tempDir"))
.sorted(Comparator.reverseOrder())
.forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
});
java复制编辑try (BufferedReader reader = new BufferedReader(new FileReader("large.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
相比 Files.lines()
,缓冲流在处理 GB 级大文件时更高效。
java复制编辑try (FileOutputStream fos = new FileOutputStream("image_copy.jpg")) {
byte[] bytes = Files.readAllBytes(Paths.get("image.jpg"));
fos.write(bytes);
}
java复制编辑import java.util.zip.*;
public class ZipExample {
public static void main(String[] args) throws IOException {
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("archive.zip"))) {
ZipEntry entry = new ZipEntry("hello.txt");
zos.putNextEntry(entry);
byte[] data = "这是文件内容".getBytes();
zos.write(data);
zos.closeEntry();
}
}
}
🖼️ 图示:ZIP 流程结构图(文件 → ZipEntry → ZipOutputStream)
java复制编辑try (ZipInputStream zis = new ZipInputStream(new FileInputStream("archive.zip"))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
Files.copy(zis, Paths.get(entry.getName()), StandardCopyOption.REPLACE_EXISTING);
}
}
java复制编辑Files.walk(Paths.get("logs"))
.filter(p -> p.toString().endsWith(".log"))
.forEach(System.out::println);
你可以使用 .filter()
方法仅处理特定类型文件(如 CSV、JSON、图片等)。
java复制编辑public class LogArchiver {
public static void main(String[] args) throws IOException {
String logFile = "server.log";
String archiveName = "log_" + System.currentTimeMillis() + ".zip";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(archiveName))) {
ZipEntry entry = new ZipEntry("server.log");
zos.putNextEntry(entry);
Files.copy(Paths.get(logFile), zos);
zos.closeEntry();
}
Files.delete(Paths.get(logFile)); // 删除原始日志
}
}
📦 示例用途:Web 应用每日归档日志 + 删除旧文件
使用 WatchService
监听文件夹变化:
java复制编辑WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("watched_folder");
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("事件类型:" + event.kind());
System.out.println("发生文件:" + event.context());
}
key.reset();
}
功能 | 对应类/方法 |
---|---|
基础检查 | File、Files.exists |
文本读写 | Files.lines / write |
目录遍历 | Files.walk() |
压缩解压 | ZipInputStream 等 |
文件监控 | WatchService |
FileChannel
) 实现大文件高速读写
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。