Skip to content
Advertisement

How to get the inmediate child directory of a file path in Java?

I want to navigate the file system and get the path to the child of a directory (if exists) without the root.

For example:

  • Input: Users/Documents/SVG
  • Output: Documents/SVG

My solution so far is to hardcode a string manipulation of the path:

JavaScript

Is there a more elegant way to do this?

Advertisement

Answer

Path.relativize() can help

JavaScript

You can convert this Path back to an File as follows

JavaScript

And you can concert any File to an Path as follows

JavaScript

For better operations on files take a look at the Files class

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement