Groovy使用 file.seperator 进行字符串分割

3

我遇到了以下错误:

Groovy script throws an exception of type class 
java.util.regex.PatternSyntaxException with message = 
Unexpected internal error near index 1
\
 ^

从Split语句如下:

 String strClassPath = System.getProperty("java.class.path");
 String[] path = strClassPath.split(System.getProperty("file.separator"));

我应该如何使这个程序在UNIX和Windows系统上都能正确运行(这就是我使用"file.separator"的原因)。
提前感谢您的帮助。

1
可能是如何在不考虑平台的情况下拆分路径?的重复问题。 - cfrick
1个回答

4

这里调用了Java的split(String regexp)方法。因此你输入的必须是一个正则表达式(或者必须加引号):

import java.util.regex.Pattern

def cp = {path, sep ->
    path.split(Pattern.quote(sep)) 
}

assert cp('C:\\window\\something\\groovy.jar', '\\') == ['C:', 'window', 'something', 'groovy.jar']
assert cp('/usr/local/share/groovy.jar', '/') == ['', 'usr', 'local', 'share', 'groovy.jar']

如果你想获取路径,使用 Path 可能更好。例如:

assert new File('/usr/local/share/groovy.jar').toPath().collect()*.toString() == ['usr', 'local', 'share', 'groovy.jar']

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