javaparsingpath

Retrieve last level directory name from path


I have a string that represents a path ... something like this:

/A/B/C/D/E/{id}/{file_name}.ext

The path structure could be different but in general I would like to retrieve last directory name (in the example {id}) before the file_name.

I would like to use Path java class.

Is there a simple and safe way to retrieve last directory name using Path class?


Solution

  • Path#getParent returns a path’s parent. You can then use Path#getFileName:

    path.getParent().getFileName();