Explain Codes LogoExplain Codes Logo

How do I obtain the file name from a String encompassing the Absolute file path?

java
file-path
string-manipulation
path-api
Nikita BarsukovbyNikita Barsukov·Feb 13, 2025
TLDR

Your absolute path can be transformed into a Path object using Paths.get(), before you call getFileName().toString() to get the file name:

String filePath = "C:/example/folder/file.txt"; String fileName = Paths.get(filePath).getFileName().toString();

Key approaches to file name extraction

Sure, we already have a quick and clean way of getting the file name. However, different situations may require different tools. Knowing some other ways to extract the file name from path would be quite handy.

Extracting using the File class

The good old java.io.File class has its way to get the file name:

File file = new File(filePath); String fileName = file.getName(); // Your file name is served, enjoy!

Extracting using String methods

Trust your basic Java knowledge. You can simply leverage String manipulation:

int lastSeparatorIndex = filePath.lastIndexOf(File.separator); String fileName = lastSeparatorIndex == -1 ? filePath : filePath.substring(lastSeparatorIndex + 1); // lastSeparatorIndex is a lifebuoy, it avoids you from drowning in the StringIndexOutOfBoundsException sea.

Ensure lastSeparatorIndex isn't -1—meaning the separator wasn't found—otherwise you're going to have a date with StringIndexOutOfBoundsException.

Dealing with different separators

It's critical to remember path separators can be different across operating systems. That's where Paths really comes to the rescue:

Path path = Paths.get(filePath); String fileName = path.getFileName().toString();

Now you don't need to lose sleep over whether you're running on Windows (\) or Unix (/).

Using Apache Commons IO

Want an easy and robust solution? Look no further than Apache Commons IO:

String fileName = FilenameUtils.getName(filePath);

This method from Apache parses the path effectively, regardless of the platform. Now you get to sip coffee instead of handling exceptions.

Flexibility with the Path API

Often, you may need to interact with different parts of the path, not just the file name. The Path API offers you that luxury:

Path parentDir = path.getParent(); // Mommy, where do we live? Path root = path.getRoot(); // I want to stay grounded. Path withoutFileName = path.subpath(0, path.getNameCount() - 1); // To the basement! File name, first door from the right.

This approach avoids having to split strings—giving you a strong and maintainable code.