Reputation: 1158
Okay I can't quite word it, but i need the following:
C:\Temp\Something\GroupName\...\file.ts -> GroupName\...\file.ts
I want to extract the path from a folder till the end.
I came up with this disaster right here, but I am sure i am reinventing the wheel.
private Path extractGroupPath(Path path, String groupName) {
int i;
for (i = 0; i < path.getNameCount(); i++) {
if (path.getName(i).startsWith(groupName)) {
break;
}
}
Path groupPath = Paths.get("");
for (; i < path.getNameCount(); i++) {
groupPath = groupPath.resolve(path.getName(i));
}
return groupPath;
}
Upvotes: 1
Views: 1303
Reputation: 1158
The answer Thomas gives is awesome and does what I needed, but in the end I decided this:
public Path extractGroupPath(Path path, String groupName) {
int startIndex = path.toString().indexOf(groupName);
String groupPath = path.toString().substring(startIndex);
return Paths.get(groupPath);
}
Because it is more simple and easy to understand.
Upvotes: 0
Reputation: 88707
To get the a relative path between to paths you can use the relativize()
method.
Thus you should be able to do this once you've found the base path, which - if you don't know it already - could be done by iterating through the parents (using getParent()
) until you find it (by checking getFilename()
) or hit the root. Then it should be as easy as parentPath.relativize(path)
.
Upvotes: 1