How to get File name from Path object In java

March 29, 2020 | No comments

Table of Content

How to get File name form Path object in Java

The Path interface is part of Java NIO introduced in Java 7. The Path interface is located in the java.nio.file package. Java NIO is the new enhanced java library to work with Files and Directories. The Path object is core part of the Java NIO, and is essential to work with the NIO api's. In this Article we explore how we can create a Path object from a String path and extract the file name represented by the path. Following code snippet show how to extract the file or directory name (String) from the path object.
Following code takes a parameter String path such as "./src/bootng/files/" pointing to a file. And extract the file name "" in this case. We first convert the stringPath to a Path Object and then if it is a regular file we use the getFileName() method which returns the the FileName and then convert it to String.
 public static String getFileName(String strPath) {
    String fileName = null;
    Path path = Paths.get(strPath);
    if (Files.isRegularFile(path)) {
      fileName = path.getFileName().toString();
    return fileName;


No comments :

Post a Comment

Please leave your message queries or suggetions.