354. Java IO API - 获取路径信息

0 阅读3分钟

354. Java IO API - 获取路径信息

Path 可以被看作是存储路径名称元素的序列。路径结构中的第一个元素位于索引 0,而最后一个元素位于索引 [n-1],其中 n 是路径中元素的数量。Java 提供了多种方法来根据这些索引获取单独的元素或路径的子序列。

示例目录结构

我们使用以下目录结构作为示例:

  • Windows: C:\home\joe\foo
  • Solaris: /home/joe/foo

基本路径操作示例

下面的代码示例定义了一个 Path 实例,并调用了多个方法来获取路径的信息:

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathInfoExample {
    public static void main(String[] args) {
        // 创建一个路径实例,Windows 路径格式
        Path pathWindows = Paths.get("C:\\home\\joe\\foo");
        
        // 创建一个路径实例,Solaris 路径格式
        Path pathSolaris = Paths.get("/home/joe/foo");
        
        // 打印路径的各种信息
        printPathInfo(pathWindows);
        printPathInfo(pathSolaris);
    }
    
    public static void printPathInfo(Path path) {
        System.out.format("toString: %s%n", path.toString());
        System.out.format("getFileName: %s%n", path.getFileName());
        System.out.format("getName(0): %s%n", path.getName(0));
        System.out.format("getNameCount: %d%n", path.getNameCount());
        System.out.format("subpath(0,2): %s%n", path.subpath(0, 2));
        System.out.format("getParent: %s%n", path.getParent());
        System.out.format("getRoot: %s%n", path.getRoot());
    }
}

方法与输出说明

以下是 Path 对象方法的详细解释和在不同操作系统下的返回值:

方法Solaris 返回值Windows 返回值说明
toString()/home/joe/fooC:\home\joe\foo返回路径的字符串表示。对于 UNIX 操作系统,会修正路径格式(例如 //home/joe/foo 会变为 /home/joe/foo)。
getFileName()foofoo返回路径的文件名(或路径中的最后一个元素)。
getName(0)homehome返回路径中指定索引位置的元素。此处为路径的第一个目录元素。
getNameCount()33返回路径中元素的数量。
subpath(0, 2)home/joehome\joe返回路径的子序列(不包含根元素),从索引 0 到索引 2(不包括索引 2)。
getParent()/home/joe\home\joe返回路径的父级目录。
getRoot()/C:\返回路径的根目录。

相对路径示例

下面是使用相对路径时的代码示例:

// Solaris 路径格式
Path pathSolarisRelative = Paths.get("sally/bar");

// Windows 路径格式
Path pathWindowsRelative = Paths.get("sally\\bar");

printPathInfo(pathSolarisRelative);
printPathInfo(pathWindowsRelative);

在 Solaris 和 Windows 中,输出结果如下:

方法Solaris 返回值Windows 返回值
toString()sally/barsally\bar
getFileName()barbar
getName(0)sallysally
getNameCount()22
subpath(0, 1)sallysally
getParent()sallysally
getRoot()nullnull

解释

  • toString(): 返回路径的字符串表示。当路径包含相对目录时,toString() 将显示相对路径,如 sally/barsally\bar
  • getFileName(): 返回路径的最后一个部分(文件名或目录名),在上述示例中是 bar
  • getName(0): 返回路径的第一个部分,这里是 sally
  • getNameCount(): 返回路径中元素的数量,显示路径中有多少级目录或文件名。
  • subpath(0, 1): 返回从索引 0 到索引 1 之间的路径子序列。
  • getParent(): 返回路径的父级目录,对于相对路径,返回的是直接上级目录。
  • getRoot(): 对于相对路径,返回 null,因为相对路径没有根目录;对于绝对路径,返回根目录(如 /C:\)。

总结

通过 Path 类提供的各种方法,您可以轻松获取路径的各个部分,包括文件名、父目录、根目录以及路径元素的子序列。这些方法在处理路径时非常有用,尤其是在需要处理跨平台文件路径的场景下。