Java NIO - Path 路径
顾名思义,路径是文件系统中文件或目录等实体的特定位置,以便人们可以在该特定位置搜索和访问它。
从 Java 技术上讲,路径是 Java 版本 7 期间在 Java NIO 文件包中引入的一个接口,是特定文件系统中位置的表示。由于路径接口位于 Java NIO 包中,因此它的限定名称为 java.nio.file.Path。
一般来说,实体的路径可以分为两种类型,一种是绝对路径,另一种是相对路径。正如这两种路径的名称所暗示的那样,绝对路径是从根到它所在的实体的位置地址,而相对路径是相对于其他路径的位置地址。路径在其定义中使用分隔符,对于 Windows 为"\",对于 unix 操作系统为"/"。
为了获取 Path 的实例,我们可以使用 java.nio.file.Paths 类的静态方法get()。此方法将路径字符串或连接起来形成路径字符串的字符串序列转换为 Path 实例。如果传递的参数包含非法字符,此方法还会抛出运行时 InvalidPathException。
如上所述,通过传递根元素和定位文件所需的完整目录列表可以检索绝对路径。而相对路径可以通过将基本路径与相对路径相结合来检索。以下示例将说明两种路径的检索
示例
package com.java.nio; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.file.FileSystem; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; public class PathDemo { public static void main(String[] args) throws IOException { Path relative = Paths.get("file2.txt"); System.out.println("Relative path: " + relative); Path absolute = relative.toAbsolutePath(); System.out.println("Absolute path: " + absolute); } }
到目前为止,我们知道了什么是路径接口,为什么我们需要它以及如何访问它。现在,我们将了解 Path 接口为我们提供的重要方法。
Path 接口的重要方法
getFileName() − 返回创建此对象的文件系统。
getName() − 返回此路径的名称元素作为 Path 对象。
getNameCount() − 返回路径中的名称元素数量。
subpath() − 返回此路径的名称元素子序列的相对 Path。
getParent() −返回父路径,如果此路径没有父路径,则返回 null。
getRoot() − 将此路径的根组件作为 Path 对象返回,如果此路径没有根组件,则返回 null。
toAbsolutePath() − 返回表示此路径绝对路径的 Path 对象。
toRealPath() − 返回现有文件的真实路径。
toFile() − 返回表示此路径的 File 对象。
normalize() − 返回此路径,该路径是已消除了冗余名称元素的路径。
compareTo(Path other) −按字典顺序比较两个抽象路径。如果参数等于此路径,则此方法返回零;如果此路径按字典顺序小于参数,则返回小于零的值;如果此路径按字典顺序大于参数,则返回大于零的值。
endsWith(Path other) − 测试此路径是否以给定路径结尾。如果给定路径有 N 个元素,没有根组件,并且此路径有 N 个或更多元素,则如果每条路径的最后 N 个元素(从距离根最远的元素开始)相等,则此路径以给定路径结尾。
endsWith(String other) −测试此路径是否以 Path 结尾,该 Path 是通过转换给定的路径字符串构建的,其方式与 endsWith(Path) 方法指定的方式完全相同。
示例
以下示例说明了上面提到的 Path 接口的不同方法 −
package com.java.nio; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.file.FileSystem; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; public class PathDemo { public static void main(String[] args) throws IOException { Path path = Paths.get("D:/workspace/ContentW/Saurav_CV.docx"); FileSystem fs = path.getFileSystem(); System.out.println(fs.toString()); System.out.println(path.isAbsolute()); System.out.println(path.getFileName()); System.out.println(path.toAbsolutePath().toString()); System.out.println(path.getRoot()); System.out.println(path.getParent()); System.out.println(path.getNameCount()); System.out.println(path.getName(0)); System.out.println(path.subpath(0, 2)); System.out.println(path.toString()); System.out.println(path.getNameCount()); Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS); System.out.println(realPath.toString()); String originalPath = "d:\data\projects\a-project\..\another-project"; Path path1 = Paths.get(originalPath); Path path2 = path1.normalize(); System.out.println("path2 = " + path2); } }