Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically update absolute path

Given the below incoming path, e.g.

C:\cresttest\parent_3\child_3_1\child_3_1_.txt

How can one update and add new dir in between above path to construct below result

C:\cresttest\NEW_PATH\parent_3\child_3_1\child_3_1_.txt

Currently I am using multiple subString to identify the incoming path, but incoming path are random and dynamic. Using substring and placing my new path requires more line of code or unnecessary processing, is there any API or way to easily update and add my new dir in between the absolute path?

like image 861
Rakesh Avatar asked Jan 18 '26 20:01

Rakesh


1 Answers

By using java.nio.file.Path, you could to the following:

Path incomingPath = Paths.get("C:\\cresttest\\parent_3\\child_3_1\\child_3_1_.txt");
//getting C:\cresttest\, adding NEW_PATH to it
Path subPathWithAddition = incomingPath.subpath(0, 2).resolve("NEW_PATH");
//Concatenating C:\cresttest\NEW_PATH\ with \parent_3\child_3_1\child_3_1_.txt
Path finalPath = subPathWithAddition.resolve(incomingPath.subpath(2, incomingPath.getNameCount()));

You could then get the path URI by calling finalPath.toUri()

Note: this doesn't depend on any names in your path, it depends on the directory depth though, which you could edit in the subpath calls.

Note 2: you could probably reduce the amount of Path instances you make to one, I made three to improve readability.

like image 102
leroydev Avatar answered Jan 20 '26 08:01

leroydev