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:

  /**
   * Return the path to the immediate child of a directory.
   *
   * @param path to a directory
   * @return path to the child without the root
   */
  public static String removeRootFolderInPath(String path) {
    ArrayList<String> tmp = new ArrayList<>(Arrays.asList(path.split("/")));
    if (tmp.size() > 1) {
      tmp.remove(0);
    }
    path = String.join("/", tmp);
    return path;
  }

Is there a more elegant way to do this?

Advertisement

Answer

Path.relativize() can help

  Path
  parent=Path.of("Users"),
  child=Path.of("Users","Documents","SVG");

  Path relative=parent.relativize(child);

You can convert this Path back to an File as follows

relative.toFile()

And you can concert any File to an Path as follows

File f=...
Path p=f.toPath();

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