Java Program to Get the name of the file from the absolute path

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Get file name from the absolute path using getName()

import java.io.File;

class Main {

  public static void main(String[] args) {

    // link to file Test.class
    File file = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Programiz\\Java Article\\Test.class");

    // get file name using getName()
    String fileName = file.getName();
    System.out.println("File Name: " + fileName);

  }
}

Output

File Name: Test.class

In the above example, we have used the getName() method of the File class to get the name of the file.


Example 2: Get the file name using string methods

We can also get the name of the file from its absolute path using the string methods.

import java.io.File;

class Main {

  public static void main(String[] args) {
    File file = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Programiz\\Java Article\\Test.class");

    // convert the file into the string
    String stringFile = file.toString();

      int index = stringFile.lastIndexOf('\\');
      if(index > 0) {
        String fileName = stringFile.substring(index + 1);
        System.out.println("File Name: " + fileName);
      }
  }
}

Output

File Name: Test.class

In the above example,

  • file.toString() - Converts the File object into the string.
  • stringFile.lastIndexOf() - Returns the last occurrence of character '\\' in stringFile. To learn more, visit Java String lastindexOf().
  • stringFile.substring(index + 1) - Returns all the substring after position index + 1. To learn more, visit Java String substring().
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges