如何将文件路径转换为文件



我正在编写一个 Jenkins 插件,我正在使用 build.getWorkspace() 来获取当前工作区的路径。问题是这会返回一个 FilePath 对象。

如何将其转换为文件对象?

虽然我没有尝试过这个,但根据javadoc,你可以获得URI,然后你可以从中创建一个文件:File myFile = new File(build.getWorkspace().toURI())

请使用 act 函数并调用您自己的 FileCallable 实现,如果您的插件应该适用于主站和从站。有关更多信息,请查看文档、"巧妙地使用 FilePath"一章或此 stackoverflow 答案。

代码示例(源):

void someMethod(FilePath file) {
    // make 'file' a fresh empty directory.
    file.act(new Freshen());
}
// if 'file' is on a different node, this FileCallable will
// be transferred to that node and executed there.
private static final class Freshen implements FileCallable<Void> {
    private static final long serialVersionUID = 1;
    @Override public Void invoke(File f, VirtualChannel channel) {
        // f and file represent the same thing
        f.deleteContents();
        f.mkdirs();
        return null;
    }
}

这种方法 File myFile = new File(build.getWorkspace().toURI())不是正确的解决方案。我不知道为什么到目前为止这一直是一个公认的人。Sascha Vetter 提到的方法是正确的,参考了官方 Jenkins javadocs

这清楚地说,我引用

与始终表示当前计算机上的文件路径的 File 不同,FilePath 表示特定代理或控制器上的文件路径。

因此,作为 Jenkins 社区的积极贡献者,我会参考 Sascha Vetter 给出的答案。

声誉点标准使我无法对正确答案投赞成票。

最新更新