在Java中,Path
类是java.nio.file
包的一部分,用于表示文件系统中的路径。以下是Path
类的一些常用方法及其用法:
-
创建Path对象:
Path path = Paths.get("C:/example/file.txt");
-
获取路径的各部分:
Path path = Paths.get("C:/example/file.txt"); System.out.println("文件名: " + path.getFileName()); // file.txt System.out.println("父路径: " + path.getParent()); // C:/example System.out.println("根路径: " + path.getRoot()); // C:\
-
路径合并:
Path basePath = Paths.get("C:/example"); Path fullPath = basePath.resolve("file.txt"); System.out.println(fullPath); // C:/example/file.txt
-
路径规范化:
Path path = Paths.get("C:/example/./file.txt"); Path normalizedPath = path.normalize(); System.out.println(normalizedPath); // C:/example/file.txt
-
路径的相对化:
Path path1 = Paths.get("C:/example/file.txt"); Path path2 = Paths.get("C:/example/folder"); Path relativePath = path1.relativize(path2); System.out.println(relativePath); // ../folder
-
检查路径是否存在:
Path path = Paths.get("C:/example/file.txt"); boolean exists = Files.exists(path); System.out.println("路径是否存在: " + exists);
-
读取文件内容:
Path path = Paths.get("C:/example/file.txt"); List<String> lines = Files.readAllLines(path); lines.forEach(System.out::println);
-
写入文件内容:
Path path = Paths.get("C:/example/file.txt"); List<String> lines = Arrays.asList("第一行", "第二行"); Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
这些方法涵盖了Path
类的大部分常用功能,帮助开发者处理文件和目录路径相关的操作。
normalize
normalize()
方法返回一个Path
对象。这个新对象是当前路径的规范化版本,去除了所有冗余的路径成分,比如.
(当前目录)和..
(上级目录)。
例如:
Path path = Paths.get("C:/example/./folder/../file.txt");
Path normalizedPath = path.normalize();
System.out.println(normalizedPath); // 输出: C:/example/file.txt
在这个例子中,normalize()
方法返回的normalizedPath
对象表示规范化后的路径,即去除了.
和..
后得到的路径。
toAbsolutePath
toAbsolutePath()
方法用于将相对路径转换为绝对路径。它返回一个 Path
对象,该对象表示调用此方法的 Path
对象的绝对路径。
绝对路径是从文件系统的根目录开始的完整路径,而相对路径则依赖于当前的工作目录。
示例代码:
Path relativePath = Paths.get("example/file.txt");
Path absolutePath = relativePath.toAbsolutePath();
System.out.println("相对路径: " + relativePath); // 输出: example/file.txt
System.out.println("绝对路径: " + absolutePath); // 输出: C:/当前工作目录/example/file.txt (具体路径依赖于当前工作目录)
在这个例子中,relativePath
是一个相对路径,通过调用 toAbsolutePath()
方法,将其转换为对应的绝对路径 absolutePath
。