How to get ddd
from the path name where the test.java resides.
File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
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.
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.
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.
Try parentname="$(basename "$(dirname "$PWD")")" .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With