Java Path getNameCount()方法及示例

来源:这里教程网 时间:2026-02-17 21:04:12 作者:

Java Path getNameCount()方法及示例

Java 7 中,Path接口被添加到Java NIO中 。 Path接口位于java.nio.file包中,所以Java Path接口的完全限定名称是java.nio.file.Path。一个Java Path实例代表文件系统中的一个路径。路径可以用来定位文件或目录。实体的路径有两种类型,一种是绝对路径,另一种是相对路径。绝对路径是指从根到实体的位置地址,而相对路径是指相对于其他路径的位置地址。

java.nio.file.PathgetNameCount() 方法用于返回路径中名称元素的数量。如果这个路径只代表一个根元素,那么该方法将返回1。

语法

int getNameCount()

参数: 此方法不接受任何参数。

返回值: 该方法返回路径中的元素数量,如果该路径只代表一个根组件,则返回1。

以下程序说明了getNameCount()方法:
程序1 :

// Java program to demonstrate// java.nio.file.Path.getNameCount() 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:/workspace/AmanCV.docx");          // call getNameCount()        int nameCount = path.getNameCount();          // print NameCount        System.out.println("NameCount in Path: "                           + nameCount);    }}

输出。

NameCount in Path: 3

程序2

// Java program to demonstrate// java.nio.file.Path.getNameCount() 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:/Resume.pdf");          // call getNameCount()        int nameCount = path.getNameCount();          // print NameCount        System.out.println("NameCount in Path: "                           + nameCount);    }}

输出。

NameCount in Path: 2

程序3

// Java program to demonstrate// java.nio.file.Path.getNameCount() 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:");          // call getNameCount()        int nameCount = path.getNameCount();          // print NameCount        System.out.println("NameCount in Path: "                           + nameCount);    }}

输出。

NameCount in Path: 1

参考文献: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#getNameCount()

相关推荐