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

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

In this example, we will learn to get the name of the file from the absolute path in Java.

Example 1: Java program to get file name from the absolute path using getName() method

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.

To learn more on file, visit Java File.


Example 2: Java program to 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 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().