简体   繁体   English

非静态等效于 java.nio.file.Paths.get()

[英]Non-static equivalent to java.nio.file.Paths.get()

Some Background: I am running a Jenkins Shared Library in sandbox mode, and I am unable to use any Java/Groovy static methods.一些背景:我在沙箱模式下运行 Jenkins 共享库,我无法使用任何 Java/Groovy 静态方法。 An easy solution would be turn-off sandbox mode, but I must use it.一个简单的解决方案是关闭沙箱模式,但我必须使用它。 Another restriction: new java.io.File(...) calls are not allowed.另一个限制:不允许new java.io.File(...)调用。

Are there any non-static functions/methods that convert a sequence of strings that when joined form a path string to a Path -- ie the behaviour of java.nio.file.Paths.get() ?是否有任何非静态函数/方法可以将连接时形成路径字符串的字符串序列转换为路径——即java.nio.file.Paths.get()的行为?

Edit: I am aware of that it can be manually done quite tediously, but I would like to see if any existing function(s) exist to do this.编辑:我知道它可以非常乏味地手动完成,但我想看看是否存在任何现有的功能来做到这一点。

Try this:试试这个:

public static Path getPath(String ... pathArr) {
    if (pathArr.length == 0)
        throw new IllegalArgumentException();
    StringBuilder path = new StringBuilder();
    for (String s : pathArr)
        path.append("/").append(s);
    return new File(path.toString()).toPath();
}

I tested, its works for paths that doesn't exist我测试过,它适用于不存在的路径

println new File("/home/usr", "x.txt").toPath()
println new File("/home/usr/", "/x.txt").toPath()
println new File("/home/usr//x.txt").toPath()
println new File("/home", "usr/x.txt").toPath()

everything above gives the result:上面的一切给出了结果:

/home/usr/x.txt

It seems like under the restriction of Groovy Sandbox, there are no such existing function(s) that can imitate the usage of java.nio.file.Paths.get(...) without creating a new file object.好像在 Groovy Sandbox 的限制下,没有这样的现有函数可以模仿java.nio.file.Paths.get(...)的用法而不创建新的file对象。 The workaround I used in my specific case of converting file 'stems' (UNIX or DOS format) into a UNIX style absolute/relative path used messy regex matching and string concatenation.我在将文件“词干”(UNIX 或 DOS 格式)转换为 UNIX 风格的绝对/相对路径的特定案例中使用的解决方法使用了凌乱的正则表达式匹配和字符串连接。 It does mimic the call of java.nio.file.Paths.get(...) .它确实模仿了java.nio.file.Paths.get(...)的调用。

def mergePaths = { String first, String... rest ->
    return first.replaceAll(/(\\$)|(\/$)/, '').replaceAll(/(\\)/, '/') + '/' +
        rest.collect { it ->
            it.replaceAll(/(^\\)|(^\/)|(\\$)|(\/$)/, '')
        }.collect { it ->
            it.replaceAll(/(\\)/, '/')
        }.join('/')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM