How to get just the parent directory name of a specific file

minil picture minil · Nov 19, 2011 · Viewed 210.7k times · Source

How to get ddd from the path name where the test.java resides.

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");

Answer

Dave Newton picture Dave Newton · Nov 19, 2011

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.