📜  Java中的路径 getName(int) 方法及示例

📅  最后修改于: 2022-05-13 01:54:29.394000             🧑  作者: Mango

Java中的路径 getName(int) 方法及示例

Java Path 接口是在Java 7 中添加到Java NIO 中的。Path 接口位于Java.nio.file 包中,因此Java Path 接口的全称是Java.nio.file.Path。 Java Path 实例表示文件系统中的路径。路径可以用来定位文件或目录。实体的路径可以有两种类型,一种是绝对路径,另一种是相对路径。绝对路径是从根到实体的位置地址,而相对路径是相对于其他路径的位置地址。
Java.nio.file.PathgetName(int index)方法,用于将该路径的名称元素作为Path 对象返回。我们将索引作为参数传递,索引表示要返回的名称元素的索引。目录层次结构中离根最近的元素的索引为 0。离根最远的元素的索引计数为 1。
句法:

Path getName(int index)

参数:此方法接受单个参数索引,即元素的索引。
返回值:此方法返回名称元素。
异常:如果索引为负数、索引大于或等于元素数或此路径有零个名称元素,则此方法抛出和异常IllegalArgumentException
下面的程序说明了 getName(int index) 方法:
方案一:

Java
// Java program to demonstrate
// java.nio.file.Path.getName(int index) method
 
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
 
        // create object of Path
        Path path
            = Paths.get("D:\\temp\\DS and algo"
                        + "\\algorithm and data struc"
                        + "\\Problem sets");
 
        // call getName(int i) to get the
        // element at index i
        Path indexpath = path.getName(3);
 
        // print ParentPath
        System.out.println("Index 3: "
                           + indexpath);
    }
}


Java
// Java program to demonstrate
// java.nio.file.Path.getName(int index) method
 
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
 
        // create object of Path
        Path path
            = Paths.get("D:\\eclipse\\configuration"
                        + "\\org.eclipse.update");
 
        // call getName(int i) to get
        // the element at index i
        Path indexpath = path.getName(2);
 
        // print ParentPath
        System.out.println("Index 2: "
                           + indexpath);
    }
}


输出:
Index 3: Problem sets

方案二:

Java

// Java program to demonstrate
// java.nio.file.Path.getName(int index) method
 
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
 
        // create object of Path
        Path path
            = Paths.get("D:\\eclipse\\configuration"
                        + "\\org.eclipse.update");
 
        // call getName(int i) to get
        // the element at index i
        Path indexpath = path.getName(2);
 
        // print ParentPath
        System.out.println("Index 2: "
                           + indexpath);
    }
}
输出:
Index 2: org.eclipse.update

参考资料: https: Java/nio/file/Path.html#getName(int)