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

In Java, it’s essential to be able to extract the file name from a given absolute path.

This is a common task in many applications, such as when processing files or logging information.

In this tutorial, we’ll look at how to extract the file name from an absolute path in Java.


The first step in getting the file name from an absolute path is to create a File object that represents the file.

This can be done using the constructor that takes a string parameter representing the absolute path of the file.

For example:

File file = new File("/path/to/file.txt");

Once we have a File object, we can use the getName() method to extract the file name.

This method returns the name of the file as a string.

For example:

String fileName = file.getName();

This will set the fileName variable to "file.txt".

If the file path does not exist or is not valid, then the getName() method will return an empty string.

Here’s a complete example that demonstrates how to extract the file name from an absolute path:

import java.io.File;

public class FileNameExtractor {
    public static void main(String[] args) {
        String path = "/path/to/file.txt";
        File file = new File(path);
        String fileName = file.getName();
        System.out.println(fileName);
    }
}

When you run this program, it will output the file name:

file.txt

In conclusion, extracting the file name from an absolute path is a straightforward task in Java.

By creating a File object and using the getName() method, you can easily extract the name of the file.