Logo
Section 1 / 12

文件与路径操作

使用 File 和 Path API 来表示主文件系统,以解析位置并检查元数据。

导入

文件与路径操作

使用 File 和 Path API 来表示主文件系统,以解析位置并检查元数据。

No configuration found for ID: 4be84d9312dd5e1f31818a6310475f3aec831e3c9028f49d1efb9f0a824b630e

No configuration found for ID: 26fca6d31aae8f6c5c4785fa8571efc62a946cbc89103adacfc2ef647c22980f

1import java.nio.file.Path; 2 3public class AbsolutePathExample { 4 public static void main(String[] args) { 5 Path relative = Path.of("config.xml"); 6 7 // 转换为绝对路径 8 Path absolute = relative.toAbsolutePath(); 9 10 System.out.println("相对路径: " + relative); 11 System.out.println("绝对路径: " + absolute); 12 } 13}
1import java.nio.file.Path; 2 3public class PathOperations { 4 public static void main(String[] args) { 5 Path baseDir = Path.of("/home/user/project"); 6 Path subDir = Path.of("src/main"); 7 8 // 1. Resolve:连接路径 9 Path fullPath = baseDir.resolve(subDir); 10 System.out.println("已解析: " + fullPath); 11 12 // 2. Normalize:移除冗余的 ".." 13 Path messyPath = Path.of("/home/user/project/./build/../src"); 14 System.out.println("已规范化: " + messyPath.normalize()); 15 16 // 3. Relativize:如何从 A 到 B? 17 Path pathA = Path.of("/home/user/docs"); 18 Path pathB = Path.of("/home/user/music/song.mp3"); 19 Path pathAtoB = pathA.relativize(pathB); 20 21 System.out.println("从文档目录到音乐目录: " + pathAtoB); 22 } 23}
1import java.nio.file.Files; 2import java.nio.file.Path; 3import java.io.IOException; 4 5public class MetadataExample { 6 public static void main(String[] args) throws IOException { 7 // 假设我们在此位置有一个文件 8 Path target = Path.of("build.gradle"); 9 10 // 检查是否存在而不抛出异常 11 if (Files.exists(target)) { 12 System.out.println("存在: 是"); 13 System.out.println("可读: " + Files.isReadable(target)); 14 System.out.println("可写: " + Files.isWritable(target)); 15 16 // 这些操作在文件访问失败时可能会抛出 IOException 17 System.out.println("大小: " + Files.size(target) + " 字节"); 18 System.out.println("最后修改时间: " + Files.getLastModifiedTime(target)); 19 } else { 20 System.out.println("文件不存在。"); 21 } 22 } 23}
1import java.io.File; 2import java.nio.file.Path; 3 4public class InteropExample { 5 public static void main(String[] args) { 6 File legacyFile = new File("legacy.txt"); 7 8 // 将 File 转换为 Path 9 Path modernPath = legacyFile.toPath(); 10 System.out.println("转换为 Path: " + modernPath); 11 12 // 将 Path 转换为 File 13 File backToFile = modernPath.toFile(); 14 System.out.println("转换回 File: " + backToFile); 15 } 16}

类和对象

读取和写入文本文件