English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java program to get the file name from the absolute path

Comprehensive Java Examples

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

Example1Use getName() to get the file name from the absolute path

import java.io.File;
class Main {
  public static void main(String[] args) {
    //Linked to the file Test.class
    File file = new File("C:\\Users\\Bhandari\\Desktop\\w3codebox\\Java Article\\Test.class");
    //Get the file name using getName()
    String fileName = file.getName();
    System.out.println("File Name:  ", + fileName);
  }
}

Output Result

File Name:  Test.class

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

To learn more about files, please visitJava File.

Example2Use string methods to get the file name

We can also use string methods to get the file name from the absolute path of the file.

import java.io.File;
class Main {
  public static void main(String[] args) {
    File file = new File("C:\\Users\\Bhandari\\Desktop\\w3codebox\\Java Article\\Test.class");
    //Convert the file to a string 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 Result

File Name:  Test.class

In the above example,

  • file.toString() - Converts a File object to a string.

  • stringFile.lastIndexOf() -Returns the last occurrence of the character '\' in stringFile. For more information, please visitJava String lastIndexOf().

  • stringFile.substring(index +1) - Return Positionindex +1All subsequent substrings. For more information, please visitJava String substring().

Comprehensive Java Examples