Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
like image 664
minil Avatar asked Sep 30 '22 10:09

minil


People also ask

What is the parent directory of a File?

With a directory, a parent directory is a directory containing the current directory. For example, in the MS-DOS path below, the "Windows" directory is the parent directory of the "System32" directory, and C:\ is the root directory.

How do I navigate to a parent directory?

There is no way to go to the parent folder right out of the search results, as that is not how it operates, however if you double-click on the quick launch search result, resulting in navigating to the folder, then press alt+up then it will go to the parent folder.

How do I get the parent directory name in Python?

Get the Parent Directory in Python Using the dirname() Method of the os Module. The dirname() method of the os module takes path string as input and returns the parent directory as output.

Where is parent directory in Linux?

Try parentname="$(basename "$(dirname "$PWD")")" .


2 Answers

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.

like image 167
Dave Newton Avatar answered Oct 02 '22 00:10

Dave Newton


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
like image 29
neves Avatar answered Oct 01 '22 23:10

neves