Java 文件与目录操作
文件与目录操作是程序开发中的常见需求。Java 提供了 File 类和 Path/Files 类来处理文件和目录。理解这些类的使用是进行文件操作的基础。本章将详细介绍 Java 中的文件与目录操作。
File 类方法(创建、删除、重命名、判断)
File 类概述
File 类(java.io.File)用于表示文件和目录的抽象路径名。
import java.io.File;
// 创建 File 对象(不创建实际文件)
File file = new File("test.txt");
File dir = new File("directory");
创建文件和目录
File file = new File("test.txt");
// 创建文件
boolean created = file.createNewFile(); // 如果文件不存在则创建
// 创建目录
File dir = new File("mydir");
boolean dirCreated = dir.mkdir(); // 创建单层目录
// 创建多层目录
File multiDir = new File("parent/child/grandchild");
boolean multiCreated = multiDir.mkdirs(); // 创建多层目录
删除文件和目录
File file = new File("test.txt");
// 删除文件
boolean deleted = file.delete(); // 删除文件或空目录
// 删除目录(必须为空)
File dir = new File("mydir");
boolean dirDeleted = dir.delete(); // 只能删除空目录
重命名和移动
File oldFile = new File("old.txt");
File newFile = new File("new.txt");
// 重命名或移动
boolean renamed = oldFile.renameTo(newFile);
判断文件属性
File file = new File("test.txt");
// 判断是否存在
boolean exists = file.exists();
// 判断是否为文件
boolean isFile = file.isFile();
// 判断是否为目录
boolean isDirectory = file.isDirectory();
// 判断是否可读
boolean canRead = file.canRead();
// 判断是否可写
boolean canWrite = file.canWrite();
// 判断是否可执行
boolean canExecute = file.canExecute();
// 判断是否隐藏
boolean isHidden = file.isHidden();
获取文件信息
File file = new File("test.txt");
// 获取文件名
String name = file.getName(); // "test.txt"
// 获取路径
String path = file.getPath(); // "test.txt"
String absolutePath = file.getAbsolutePath(); // 绝对路径
// 获取父目录
String parent = file.getParent(); // null 或父目录路径
File parentFile = file.getParentFile();
// 获取文件大小(字节)
long length = file.length();
// 获取最后修改时间
long lastModified = file.lastModified(); // 时间戳
Date date = new Date(lastModified);
列出目录内容
File dir = new File("directory");
// 列出文件和目录名
String[] names = dir.list();
// 列出文件和目录对象
File[] files = dir.listFiles();
// 使用过滤器
File[] txtFiles = dir.listFiles((dir1, name) -> name.endsWith(".txt"));
Path / Files 类(Java 7 NIO)
Path 接口
Path 接口(java.nio.file.Path)是 Java 7 引入的,用于表示文件系统路径。
import java.nio.file.Path;
import java.nio.file.Paths;
// 创建 Path 对象
Path path = Paths.get("test.txt");
Path absolutePath = Paths.get("/home/user/test.txt");
// 组合路径
Path base = Paths.get("/home/user");
Path file = base.resolve("test.txt"); // /home/user/test.txt
// 获取路径组成部分
Path parent = path.getParent();
Path fileName = path.getFileName();
Path root = path.getRoot();
Files 类
Files 类提供了丰富的静态方法操作文件和目录。
创建文件和目录
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
// 创建文件
Path file = Paths.get("test.txt");
Files.createFile(file);
// 创建目录
Path dir = Paths.get("mydir");
Files.createDirectory(dir);
// 创建多层目录
Path multiDir = Paths.get("parent/child/grandchild");
Files.createDirectories(multiDir);
删除文件和目录
// 删除文件
Files.delete(file);
// 安全删除(不存在不抛异常)
Files.deleteIfExists(file);
// 删除目录(必须为空)
Files.delete(dir);
复制和移动
Path source = Paths.get("source.txt");
Path dest = Paths.get("dest.txt");
// 复制文件
Files.copy(source, dest);
// 移动文件(重命名)
Files.move(source, dest);
// 复制时指定选项
Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
读取和写入
Path file = Paths.get("test.txt");
// 读取所有字节
byte[] bytes = Files.readAllBytes(file);
// 读取所有行
List<String> lines = Files.readAllLines(file);
// 写入字节
Files.write(file, bytes);
// 写入行
List<String> content = Arrays.asList("line1", "line2");
Files.write(file, content);
获取文件属性
Path file = Paths.get("test.txt");
// 判断是否存在
boolean exists = Files.exists(file);
// 判断是否为文件/目录
boolean isFile = Files.isRegularFile(file);
boolean isDirectory = Files.isDirectory(file);
// 获取文件大小
long size = Files.size(file);
// 获取最后修改时间
FileTime lastModified = Files.getLastModifiedTime(file);
// 获取文件属性
BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);