在 Java 中操作文件系统:从基础到高级技术
文件系统操作是编程中的基本任务之一。Java 为开发者提供了强大而灵活的工具来管理文件和目录。在本文中,我们将详细讲解如何使用 Java 操作文件系统,既使用经典的 java.io 包,也使用现代的 java.nio.file 包。您将学习如何创建、读取、写入文件,管理目录以及处理异常。
Java 文件操作基础:File 类
java.io.File 类是 Java 中文件系统操作的基石。它表示文件或目录路径的抽象表示。重要的是要理解,File 并不存储文件内容,而只提供检查属性和执行操作的方法。
让我们看看 File 的基本操作:
import java.io.File;import java.io.IOException;
public class FileExample { public static void main(String[] args) { // 创建 File 对象 File file = new File("example.txt"); File directory = new File("myDirectory");
// 检查是否存在 System.out.println("文件存在:" + file.exists()); System.out.println("文件夹存在:" + directory.exists());
// 创建新文件 try { if (file.createNewFile()) { System.out.println("文件已创建:" + file.getName()); } else { System.out.println("文件已存在"); } } catch (IOException e) { System.err.println("创建文件时出错:" + e.getMessage()); }
// 创建目录 if (directory.mkdir()) { System.out.println("文件夹已创建:" + directory.getName()); }
// 获取文件信息 System.out.println("绝对路径:" + file.getAbsolutePath()); System.out.println("文件大小:" + file.length() + " 字节"); System.out.println("可读:" + file.canRead()); System.out.println("可写:" + file.canWrite());
// 删除文件 if (file.delete()) { System.out.println("文件已删除"); } }}File 类还允许处理目录中的文件列表:
File currentDir = new File(".");String[] contents = currentDir.list();for (String item : contents) { System.out.println(item);}文件的读取和写入:输入输出流
为了直接处理文件内容,Java 使用输入输出流(I/O streams)。处理文本文件的主要类是 FileReader/FileWriter 和 BufferedReader/BufferedWriter。
逐行读取文件
import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;
public class ReadFileExample { public static void main(String[] args) { String fileName = "input.txt"; try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println("读取文件时出错:" + e.getMessage()); } }}请注意 try-with-resources 结构。它会自动关闭流,从而防止资源泄漏。
写入文件
import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;
public class WriteFileExample { public static void main(String[] args) { String fil