Home > Software design >  How to get the inmediate child directory of a file path in Java?
How to get the inmediate child directory of a file path in Java?

Time:04-05

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?

CodePudding user response:

Take a look at Path.subpath().

public static void main(String[] args) {
    String strPath = "Users\\Documents\\SVG";
    System.out.println(getChild(strPath));
}

public static Path getChild(String str) {
    Path path = Path.of(str);
    if (path.getNameCount() < 1) { // impossible to extract child's path
        throw new MyException();
    }
    return path.subpath(1, path.getNameCount());
}

Output

Documents\SVG

CodePudding user response:

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

  • Related