How do I obtain the file name from a String encompassing the Absolute file path?
Your absolute path can be transformed into a Path
object using Paths.get()
, before you call getFileName().toString()
to get the file name:
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:
Extracting using String
methods
Trust your basic Java knowledge. You can simply leverage String manipulation:
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:
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:
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:
This approach avoids having to split strings—giving you a strong and maintainable code.
Was this article helpful?