Groovy将路径拆分为名称和父级

6
我将尝试将路径拆分为父目录和文件名。
在尝试时,您可以使用以下代码:
String path = "/root/file"
File file = new File(path)

println("Name: " + file.name)
println("Parent: " + file.parent)

我们需要获取...
Name: file
Parent: /root

对于Windows路径 C:\\root\\file.exe,我们得到:

Name: C:\root\file.exe
Parent: null

这是预期的行为吗?如果是,那么我如何在Windows路径中获得相同的结果?(如果可能,请不要使用正则表达式)

这个Java的答案(https://dev59.com/DnA65IYBdhLWcg3w8zjt)也适用于Groovy。 - BalRog
1个回答

2

使用 .replace 将 "\" 替换为 "/"

String path = "C:\\root\\file.exe"
path = path.replace("\\","/")
File file = new File(path)

println("Name: " + file.name)
println("Parent: " + file.parent)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接