I'm writing a Jenkins plugin and i'm using build.getWorkspace()
to get the path to the current workspace. The issue is that this returns a FilePath object.
How can i convert this to a File object?
I'm writing a Jenkins plugin and i'm using build.getWorkspace()
to get the path to the current workspace. The issue is that this returns a FilePath object.
How can i convert this to a File object?
Please use the act function and call your own FileCallable implementation if your plugin should work for master and slaves. For more information check the documentation, chapter "Using FilePath smartly" or this stackoverflow answer.
Code example (source):
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;
}
}
Although I haven't tried this, according to the javadoc you can obtain the URI from which you can then create a file: File myFile = new File(build.getWorkspace().toURI())
build.workspace.getRemote()
instead. –
Lyndialyndon Please use the act function and call your own FileCallable implementation if your plugin should work for master and slaves. For more information check the documentation, chapter "Using FilePath smartly" or this stackoverflow answer.
Code example (source):
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;
}
}
This approach
File myFile = new File(build.getWorkspace().toURI())
is not the correct solution. I don't know why this has been an accepted anwser till date.
The approach mentioned by Sascha Vetter is correct, taking the reference from official Jenkins javadocs
,which clearly says and I quote
Unlike File, which always implies a file path on the current computer, FilePath represents a file path on a specific agent or the controller.
So being an active contributor to Jenkins community, I would reference the answer given by Sascha Vetter.
PS. Reputation point criteria makes me unable to up-vote the correct answer.
© 2022 - 2024 — McMap. All rights reserved.
File
object?FilePath
is actually a pretty expressive API, and is specifically built for handling remote file operations. If you try accessing the workspace usingFile
on a remote slave agent, you're "gonna have a bad time". – Jarietta