I have a String
that provides an absolute path to a file (including the file name). I want to get just the file's name. What is the easiest way to do this?
It needs to be as general as possible as I cannot know in advance what the URL will be. I can't simply create a URL object and use getFile()
- all though that would have been ideal if it was possible - as it's not necessarily an http://
prefix it could be c:/ or something similar.
Here are 2 ways(both are OS independent.)
Using Paths
: Since 1.7
Path p = Paths.get(<Absolute Path of Linux/Windows system>);
String fileName = p.getFileName().toString();
String directory = p.getParent().toString();
Using FilenameUtils
in Apache Commons IO :
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
Apache Commons IO provides the FilenameUtils class which gives you a pretty rich set of utility functions for easily obtaining the various components of filenames, although The java.io.File class provides the basics.
From Apache Commons IO FileNameUtils
String fileName = FilenameUtils.getName(stringNameWithPath);
new File(absolutePath).getName();
Source: Stackoverflow.com