Java Path getFileName()方法及示例

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

Java Path getFileName()方法及示例

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

java.nio.file.PathgetFileName() 方法用于返回该路径对象所指向的文件或目录的名称。文件名是目录层次结构中离根最远的元素。

语法

Path getFileName()

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

返回值: 该方法返回该路径对象所指向的文件或目录的名称。

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

// Java program to demonstrate// java.nio.file.Path.getFileName() 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 getFileName() and get FileName path object        Path fileName = path.getFileName();          // print FileName        System.out.println("FileName: "                           + fileName.toString());    }}

输出。

FileName: AmanCV.docx

程序2

// Java program to demonstrate// java.nio.file.Path.getFileName() 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 getFileName() and get FileName path object        Path fileName = path.getFileName();          // print FileName        System.out.println("FileName: "                           + fileName.toString());    }}

输出。

FileName: Resume.pdf

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

相关推荐