Categories: java, groovy

How to create middle folders on an already existing path?

2 answers

I have a path like this:

/foo/bar/... (can contain other subdirs or files) 

I want to add a "middle" folder in the mid of said path, leading to:


What's an elegant way to do that?

All answers to this question, which has the identifier 61102633

The best answer:

Yeah so what you can do is have a path like the following that represents the absolute path of foo/bar/

Path path = Paths.get("foo", "bar"); 

Then you can get the parent of the current path.

Path parent = path.getParent(); 

Then you can resolve a sibling, a new path.

Path newChild = parent.resolve("middle"); 

Then you cna create that path if it doesnt exist.


Not sure what you have, or what you want, but assuming your path is a String

def path = "/foo/bar/baz/whee/yay" 

You could just split the string on /

def segments = path.split('/') 

insert one at position 2 (split has left us an empty entry before the initial /)

def inserted = segments[0..1] + 'new' + segments[2..-1] 

Then join them back together

assert inserted.join('/') == '/foo/new/bar/baz/whee/yay' 

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type is referenced as an interface from”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data