Search code examples
groovyxcopy

I want to simply copy the file by executing xcopy command using groovy


I want to copy a file whose source and destinations are stored in variables.

def  gitPath = 'C:\\demo1\\'
def  ServerPath= 'D:\\demo\\git1\\' 
def  file = 'Sports/Badminton/Players/Saina.txt'
def  command = "xcopy /y $gitPath$file $ServerPath$file /Q"

def copyManuscriptsCommandExecute =command.execute();

def cmcErr = new StringBuffer()
copyManuscriptsCommandExecute.consumeProcessErrorStream(cmcErr)

  def copyManuscriptsCommandExecuteOutput=copyManuscriptsCommandExecute.text
        println "Copy Manuscripts Command Execution Output: "+copyManuscriptsCommandExecuteOutput
        println "Copy Manuscripts Command Execution Error: "+cmcErr.toString() 

I am getting error as invalid parameters.IF I use def file = 'Sports\\Badminton\\Players\\Saina.txt' then it is working fine.However i am getting the value of variable file from the output of a command execution so i can't change that. Is there a way to fix this?


Solution

  • You need to convert unix path separator to windows like \.

     ...
    
     file = normalize(file)
     def command = "xcopy /y $gitPath$file $ServerPath$file /Q"
    ...
    static String normalize(String s) {
        s.replaceAll('/', File.separator)
    }
    

    Just normalize the separator before using the string read from command line.