cesarsotovalero
cesarsotovalero

Reputation: 1327

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:

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?

Upvotes: 0

Views: 1805

Answers (2)

Sync it
Sync it

Reputation: 1198

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

Upvotes: 1

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28968

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

Upvotes: 1

Related Questions