Search code examples
java-streamjenkins-pipelinejenkins-groovy

Jenkins pipeline script to copy or move file to another destination


I am preparing a Jenkins pipeline script in Groovy language. I would like to move all files and folders to another location. As Groovy supports Java so I used below java code to perform the operation.

pipeline{
 agent any    
    
 stages{    
     stage('Organise Files'){                         
         steps{  
                script{                        
                    File sourceFolder = new File("C:\\My-Source");
                    File  destinationFolder = new File("C:\\My-Destination");                                                   
                    File[] listOfFiles = sourceFolder.listFiles();
                    echo "Files Total: " + listOfFiles.length;  

                    for (File file : listOfFiles) {
                        if (file.isFile()) {
                            echo file.getName()                                                                
                            Files.copy(Paths.get(file.path), Paths.get("C:\\My-Destination"));                                   
                        }
                    }                  
                }                                
            }                           
        } 
    }
}

This code throws the bellow exception:

groovy.lang.MissingPropertyException: No such property: Files for class: WorkflowScript

I tried with below code too, but it's not working either.

FileUtils.copyFile(file.path, "C:\\My-Destination");

Finally, I did try with java I/O Stream to perform the operation and the code is bellow:

def srcStream = new File("C:\\My-Source\\**\\*").newDataInputStream()
def dstStream = new File("C:\\My-Destination").newDataOutputStream()
dstStream << srcStream
srcStream.close()
dstStream.close()

But it's not working either and throws the below exception:

java.io.FileNotFoundException: C:\My-Source (Access is denied)

Can anyone suggest me how to solve the problem and please also let me know how can I delete the files from the source location after copy or move it? One more thing, during the copy can I filter some folder and files using wildcard? Please also let me know that.


Solution

  • Don't execute these I/O functions using plain Java/Groovy. Even if you get this running, this will always be executed on the master and not the build agents. Use pipeline steps also for this, for example:

    bat("xcopy C:\\My-Source C:\\My-Destination /O /X /E /H /K")
    

    or using the File Operations Plugin

    fileOperations([fileCopyOperation(
      excludes: '',
      flattenFiles: false,
      includes: 'C:\\My-Source\\**',
      targetLocation: "C:\\My-Destination"
    )]).
    

    I assume I didn't hit the very right syntax for Windows paths here in my examples, but I hope you get the point.