How to get just the parent directory name of a specific file
Solution 1:
Use File
's getParentFile()
method and String.lastIndexOf()
to retrieve just the immediate parent directory.
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()
:
FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd
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.
Solution 2:
Since Java 7 you have the new Paths api. The modern and cleanest solution is:
Paths.get("C:/aaa/bbb/ccc/ddd/test.java").getParent().getFileName();
Result would be:
C:/aaa/bbb/ccc/ddd