英文:
How to create middle folders on an already existing path?
问题
我有一个路径如下:
/foo/bar/...(可以包含其他子目录或文件)
我想在该路径中间添加一个“middle”文件夹,变成:
/foo/middle/bar/...
有没有一种优雅的方法来实现这个?
英文:
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:
/foo/middle/bar/...
What's an elegant way to do that?
答案1
得分: 0
好的,以下是翻译好的部分:
是的,你可以这样做,有一个类似以下的路径,表示了 foo/bar/
的绝对路径:
Path path = Paths.get("foo", "bar");
然后你可以获取当前路径的父路径。
Path parent = path.getParent();
接着,你可以解析一个同级的新路径。
Path newChild = parent.resolve("middle");
然后,如果该路径不存在,你可以创建这个路径。
Files.createDirectory(newChild);
英文:
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.
Files.createDirectory(newChild);
答案2
得分: 0
不确定您拥有什么或想要什么,但假设您的路径是一个字符串
def path = "/foo/bar/baz/whee/yay"
您可以通过在“/”上拆分字符串来实现
def segments = path.split('/')
在位置2插入一个元素(拆分后在初始“/”之前留下了一个空条目)
def inserted = segments[0..1] + 'new' + segments[2..-1]
然后将它们重新连接在一起
assert inserted.join('/') == '/foo/new/bar/baz/whee/yay'
英文:
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'
专注分享java语言的经验与见解,让所有开发者获益!
评论