Mark's comment is a better solution thanlastIndexOf():
file.getParentFile().getName();
These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent File). When getParentFile() is null you'll need to resort to using lastIndexOf, or use something like Apache Commons' FileNameUtils.getFullPath():
There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils class to grab the name from the result, use lastIndexOf, etc.
Use
File
'sgetParentFile()
method andString.lastIndexOf()
to retrieve just the immediate parent directory.Mark's comment is a better solution than
lastIndexOf()
:These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent
File
). WhengetParentFile()
is null you'll need to resort to usinglastIndexOf
, or use something like Apache Commons'FileNameUtils.getFullPath()
:There are several variants to retain/drop the prefix and trailing separator. You can either use the same
FilenameUtils
class to grab the name from the result, uselastIndexOf
, etc.Use below,