'How to print a file path in reverse order in Java?

I want to print the relative path of file/folder in reverse order.

IPath projectRelativePath = element.getProjectRelativePath();

the result is "src/abc/foldername".

But I want the result in reverse manner ie. foldername/abc/src.

Can someone help me here? Is there any JAVA API available for this?



Solution 1:[1]

A Stream of the Path components could be used to reverse the components of a relative path, and also handles any platform using the appropriate file separator:

Stream.iterate(Path.of("src/abc/foldername"), Path::getParent)
      .takeWhile(Objects::nonNull)
      .map(Path::getFileName).map(Path::toString)
   .collect(Collectors.joining(File.separator));
==> "foldername/abc/src"  (or foldername\abc\src on Windows)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DuncG